Python 如何使matplotlib图形中的标题和图例区域不透明?

Python 如何使matplotlib图形中的标题和图例区域不透明?,python,matplotlib,legend,title,osmnx,Python,Matplotlib,Legend,Title,Osmnx,编辑:我在下面的示例中遇到的问题,我也可以使用以下内容重新创建: 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') patc

编辑:我在下面的示例中遇到的问题,我也可以使用以下内容重新创建:

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笔记本复制并粘贴图像,则标题、图例和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笔记本外的图像时,无法得到标题和图例所在的区域是不透明的。它看起来不错,但只要我把它复制粘贴到外面,主体图形上方的区域就会保持透明。 我尝试了各种与facecolor和alpha的组合,但都没有成功

我想要实现的是,当我从Jupyter笔记本中复制粘贴它时,整个东西都有一个白色背景

使用下面的代码,标题的背景为白色,但仅限于文本所在的位置

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()
编辑:我想要的和作为结果图片的我拥有的:()

希望有人能帮我让它工作!
非常感谢您提供的任何帮助

运行您共享的小代码示例可以完美地再现您所面临的问题。结果与默认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]);


您可以通过在创建地物时添加
facecolor
参数来更改此设置(剩余的黑色背景不是地物png的一部分):


如果图形不是使用
plt.子批次生成的(例如,当使用另一个包,如pandas或seaborn时):


我不确定你的任务是什么。你能提供当前图表的图片吗?此外,您能否提供受访者可以复制的数据?由于您没有提供我们可以轻松复制粘贴测试的数据,因此很难回答您的问题。如果您不习惯创建可复制的小绘图,我邀请您从中复制一个,以再现您所面临的问题。并且发布几张图片(问题和预期结果)将是一个加号。也许您只需要
fig.set\u facecolor('white')
。感谢您的反馈,我将尝试在不需要额外软件包的情况下,使用较小的集合重现此问题。我已经使它比我的整个脚本小,但是没有考虑运行这个脚本所必需的osmnx包。(安装了这个软件包后,这个脚本应该可以运行)我添加了我想要的和我拥有的图片。我试图基于matplotlib示例创建一个可复制的小示例,但无法重新创建我的问题。安装了OSMNX包后,我的代码应该使用复制粘贴运行。现在,我还添加了一个非常基本的示例,该示例也有相同的问题。希望如果有人解决了这个问题,我可以在我的实际案例中重用这个解决方案。。我所做工作的最终结果可以在这里找到:
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]);
# If you have an Axes object:
ax.figure.set_facecolor('white')

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