繁体   English   中英

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

[英]How to make title and legend area in a matplotlib figure not transparent?

编辑:我在下面的示例中遇到的问题我也可以用这个重新创建:

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-label 具有透明背景。 我希望创建的图像的整个区域都具有纯白色背景。 就像 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

希望有人可以帮助我让它工作! 任何帮助是极大的赞赏

运行您共享的小代码示例可以完美地重现您面临的问题。 结果与默认的 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参数来更改此设置(剩余的黑色背景不是图形 png 的一部分):

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生成的(例如,当使用另一个 package 像 pandas 或 seaborn 时):

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM