Skip to main content
 首页 » 编程设计

python之如何为透明背景的图形调整某些特征的颜色

2024年10月25日13飞鱼

我正在保存具有透明背景的图以粘贴到深色背景上。我可以解决大部分问题,但有两件事我不知道如何“照亮”以使其可见。

1) 图中每个图的轴方框。

2) 那个黑色的小东西“1e11”。

我想如果这样更简单的话,我想把所有的图都做成一样的,但现在如果有办法分别做每一个图(例如,一个图的红色边框,另一个图的绿色边框),我的兴趣就会激起。

import matplotlib.pyplot as plt 
import numpy as np 
 
tau = 2.*np.pi 
 
theta = np.linspace(0, tau) 
x = 1.4E+11 + 0.9E+10 * np.cos(theta) 
y = 3.3E+10 + 4.5E+09 * np.sin(theta) 
 
fig = plt.figure(figsize=(10,5)) 
fig.patch.set_alpha(0.0) 
 
ax1 = fig.add_axes([0.08, 0.15, 0.4, 0.8]) 
ax2 = fig.add_axes([0.55, 0.15, 0.4, 0.8]) 
 
grey1 = (0.5, 0.5, 0.5) 
grey2 = (0.7, 0.7, 0.7) 
 
ax1.patch.set_facecolor(grey1) 
ax1.patch.set_alpha(1.0) 
 
ax1.set_xlabel('time (sec)', fontsize = 16, color=grey2) 
ax1.tick_params(axis='both', which='major', labelsize = 16, colors=grey2) 
 
ax1.plot(x, y) 
 
plt.savefig('nicefig')   # don't need: transparent=True 
plt.show() 

请您参考如下方法:

最简单的方法是更改​​默认设置:

import matplotlib.pyplot as plt 
import numpy as np 
 
# define colors 
grey1 = (0.5, 0.5, 0.5) 
grey2 = (0.7, 0.7, 0.7) 
 
plt.rcParams['lines.color'] = grey2 
plt.rcParams['xtick.color'] = grey2 
plt.rcParams['ytick.color'] = grey2 
plt.rcParams['axes.labelcolor'] = grey2 
plt.rcParams['axes.edgecolor'] = grey2 
 
# the rest of your code goes here .... 

结果:

但是,这会将更改应用于所有轴。因此,如果您想在 ax2 上保留标准颜色,则必须深入研究坐标区对象并为所有线条和文本元素找到相应的艺术家:

# all your plotting code goes here ... 
 
# change the box color 
plt.setp(ax1.spines.values(), color=grey2) 
 
# change the colors of the ticks 
plt.setp([ax1.get_xticklines(), ax1.get_yticklines()], color=grey2) 
 
# change the colors of the labels 
plt.setp([ax1.xaxis.get_label(), ax1.yaxis.get_label()], color=grey2) 
 
# change the color of the tick labels 
plt.setp([ax1.get_xticklabels(), ax1.get_yticklabels()], color=grey2) 
 
# change the color of the axis offset texts (the 1e11 thingy) 
plt.setp([ax1.xaxis.get_offset_text(), ax1.yaxis.get_offset_text()], color=grey2) 
 
plt.show() 

结果: