如何使Matplotlib图像中的标题和图例区域不透明?

5

编辑:我在下面的示例中遇到问题,我也可以通过以下方式重现该问题:

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.ylabel('Y-label');
plt.figtext(0.4, 1.1,'Title:',fontsize=40, color='black',ha ='left',  backgroundcolor='white')
patch_example=mpatches.Patch(color='green', label='label')
plt.legend(fontsize=16, loc='upper center',bbox_to_anchor=(0.5, 1.2), handles=[patch_example])

如果你从Jupyter Notebook中复制并粘贴图像,则标题、图例和y标签将具有透明背景。我希望整个图像区域都具有实心白色背景,就像matplotlib示例中的此示例一样:

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)


plt.rcdefaults()
fig, ax = plt.subplots()

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
y_pos = np.arange(len(people))
performance = 3 + 10 * np.random.rand(len(people))
error = np.random.rand(len(people))

ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(people)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')

plt.show()

我尝试了各种方式,但是无法在将图像从Jupyter Notebook复制粘贴到外部时使标题和图例所在区域不透明。看起来一切正常,但是一旦我将其复制粘贴到外部,主要图像上方的区域便会保持透明。
我尝试使用facecolor和alpha对图例进行各种组合,但没有成功。
我想要实现的是,在我将其从Jupyter Notebook复制粘贴出来时,整个东西都有白色背景。
使用下面的代码,标题具有白色背景,但仅限于文本所在的位置。
import osmnx as ox
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib as mpl
import string
%matplotlib inline  

Address='Kerkstraat, Amersfoort'

# Give each streettype a color based on the name. If both names occur (eg: Rijksstraatweg), first one in the list wins
def colourcode(x):
        # if (your_street in x):
    if x==your_street:
        return '#ff6200'
    elif ('laan' in x): 
        return 'green'
    else:
        return 'gainsboro'
# Give the input street a wider linewidth
def linethick(x):
    if x==your_street: return 7
    else: return 1
   
    # USE THE USER INPUT TO CREATE A GRAPH AROUND THAT ADDRESS
G3 = ox.graph_from_address(Address, network_type='all',dist=200, dist_type='bbox', simplify=False)
edge_attributes = ox.graph_to_gdfs(G3, nodes=False)
    
    # Color every street based on the streettype. First split the address into street and city
your_street=Address.split(',',1)[0].lower()
city=Address.split(',',1)[1].lower().strip()
ec = [colourcode(str(row['name']).lower()) for index, row in edge_attributes.iterrows()]
lw = [linethick(str(row['name']).lower()) for index, row in edge_attributes.iterrows()]
    
#Create figure
fig,ax= ox.plot.plot_graph(G3, bgcolor='white', ax=None, node_size=0, node_color='w', node_edgecolor='gray', node_zorder=2,
                        edge_color=ec, edge_linewidth=lw, edge_alpha=1, figsize=(25,25), dpi=300 , show=False, close=False)
    
# ADD TITLE AND LEGEND: I WANT TO GET A WHITE BACKGROUND FOR THE PART WITH TITLES AND LEGEND 
#Titles
plt.figtext(0.4, 0.94,'Your Street: ' + string.capwords(your_street), fontsize=40, color='#ff6200',ha ='left',  backgroundcolor='white')
plt.figtext(0.4, 0.97, 'Your Place: ' + string.capwords(city), fontsize=40, color='black',ha ='left',  backgroundcolor='white')
    
#Legends
your_street_patch=mpatches.Patch(color='#ff6200', label='Your Street')
lane_patch =mpatches.Patch(color='green', label='Laan')
anders_patch =mpatches.Patch(color='gainsboro', label='Anders')
#create your street legend
first_legend=plt.legend(fontsize=16, frameon=False, bbox_to_anchor=(0.5, 1.07), loc='upper center',handles=[your_street_patch])
# Add the legend manually to the current Axes.
ax = plt.gca().add_artist(first_legend)
# Create another legend for the rest
plt.legend(fontsize=16, frameon=False,loc='upper center',bbox_to_anchor=(0.5, 1.05), ncol=8, handles=[lane_patch,anders_patch])

#show everything
plt.show()

编辑:我想要的和作为结果图片的是什么:(https://imgur.com/a/osPQAsp)

希望有人能够帮助我让它正常工作!非常感谢任何帮助。


1
我不确定你负责的状态。你能提供当前图形的图片吗?此外,你能提供受访者可以重现的数据吗? - r-beginners
很难回答你的问题,因为你没有提供一个_小的可重现的_示例,我们可以轻松地复制粘贴来测试。如果你不习惯创建小的可重现的图形,我建议你从matplotlib画廊中复制一个能够重现你所面临问题的图形。同时,发布一些图片(问题和期望结果)会更好。也许你需要的只是fig.set_facecolor('white') - Patrick FitzGerald
感谢您的反馈,我将尝试使用更小的数据集来复现问题,以避免需要额外的软件包。我已经将数据集缩小到比整个脚本小,但没有考虑到运行此脚本所需的osmnx软件包。(安装该软件包后,此脚本应该可以运行) - Sanne Hombroek
现在我还添加了一个非常基本的例子,它有相同的问题。希望如果有人为此解决了它,我可以将该解决方案重用于我的实际情况。我正在做的最终结果可以在这里找到:https://sannehombroek.github.io/nbinteract-tutorial/streetcolors4.html - Sanne Hombroek
你尝试按照我在上一条评论中建议的更改facecolor了吗?无论如何,感谢您抽出时间提供一个小的可复制代码示例和图片。另外,请注意,为了让评论者收到您的回复通知,您必须包括“@用户名”(这就是我回复晚的原因)。正如您所看到的,由于我是在您的问题下发表评论,因此我不需要添加此内容。 - Patrick FitzGerald
显示剩余2条评论
1个回答

6

运行您分享的小代码示例可以完美地重现您面临的问题。结果与默认的 matplotlib 绘图参数一致。

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
plt.ylabel('Y-label')
plt.figtext(0.4, 1.1, 'Title:', fontsize=40, color='black', ha ='left',
            backgroundcolor='white')
patch_example = mpatches.Patch(color='green', label='label')
plt.legend(fontsize=16, loc='upper center', bbox_to_anchor=(0.5, 1.2),
           handles=[patch_example]);

np_background


您可以在创建图形时添加facecolor参数来更改这个(剩余的黑色背景不是图形的一部分):

fig, ax = plt.subplots(facecolor='white')

plt.ylabel('Y-label')
plt.figtext(0.4, 1.1,'Title:', fontsize=40, color='black', ha ='left',
            backgroundcolor='white')
patch_example = mpatches.Patch(color='green', label='label')
plt.legend(fontsize=16, loc='upper center', bbox_to_anchor=(0.5, 1.2),
           handles=[patch_example]);

白色背景


如果图表不是使用plt.subplots生成的(例如使用其他包,如pandas或seaborn):

# If you have an Axes object:
ax.figure.set_facecolor('white')

# If you don't:
plt.gcf().set_facecolor('white')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接