Uni*_*est 5 python matplotlib pandas
是否可以将图表外的区域设置为黑色?我将图表区域设置为黑色,但外部区域为灰色。如果它们不可见,我可以将其更改为黑色,并且可以将轴颜色设置为白色吗?
我做了一个这样的图表:
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()
Run Code Online (Sandbox Code Playgroud)
您所指的边框可以使用该facecolor
属性进行修改。使用代码修改此内容的最简单方法是使用:
plt.gcf().set_facecolor('white') # Or any color
Run Code Online (Sandbox Code Playgroud)
或者,如果您手动创建图窗,则可以使用关键字参数来设置它。
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()
Run Code Online (Sandbox Code Playgroud)
另一个比@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()
Run Code Online (Sandbox Code Playgroud)
上面的代码产生 .
您可以运行plt.style.available
以打印可用样式列表,并享受这些样式的乐趣。