更改图表边框区域颜色
可以把图表外面的区域设置成黑色吗?我把图表的区域设置成黑色了,但外面还是灰色的。我能把外面也改成黑色吗?如果坐标轴不明显的话,能把坐标轴的颜色改成白色吗?
我做了一个这样的图表:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
test = pd.DataFrame(np.random.randn(100,3))
chart = test.cumsum().plot()
chart.set_axis_bgcolor('black')
plt.show()
2 个回答
6
还有一种解决方案,虽然不如@Ffisegydd的答案灵活,但更简单。你可以使用pyplot模块中预定义的样式'dark_background',这样就能达到类似的效果。代码如下:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# use style 'dark_background'
plt.style.use('dark_background')
test = pd.DataFrame(np.random.randn(100,3))
chart = test.cumsum().plot()
#chart.set_axis_bgcolor('black')
plt.show()
上面的代码会生成 。
附注
你可以运行 plt.style.available
来打印出可用样式的列表,玩得开心哦!
参考资料
5
你提到的边框可以通过 facecolor
这个属性来修改。最简单的方法就是在你的代码中使用:
plt.gcf().set_facecolor('white') # Or any color
另外,如果你手动创建图形的话,也可以通过关键字参数来设置它。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
test = pd.DataFrame(np.random.randn(100,3))
bkgd_color='black'
text_color='white'
fig = plt.figure(facecolor=bkgd_color)
ax = fig.add_subplot(1, 1, 1)
chart = test.cumsum().plot(ax=ax)
chart.set_axis_bgcolor(bkgd_color)
# Modify objects to set colour to text_color
# Set the spines to be white.
for spine in ax.spines:
ax.spines[spine].set_color(text_color)
# Set the ticks to be white
for axis in ('x', 'y'):
ax.tick_params(axis=axis, color=text_color)
# Set the tick labels to be white
for tl in ax.get_yticklabels():
tl.set_color(text_color)
for tl in ax.get_xticklabels():
tl.set_color(text_color)
leg = ax.legend(loc='best') # Get the legend object
# Modify the legend text to be white
for t in leg.get_texts():
t.set_color(text_color)
# Modify the legend to be black
frame = leg.get_frame()
frame.set_facecolor(bkgd_color)
plt.show()