更改图表边框区域颜色

时间:2014-05-03 12:29:03

标签: 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()

2 个答案:

答案 0 :(得分:3)

您可以使用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()

Plot

答案 1 :(得分:3)

另一种解决方案不如@ 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()

以上代码生成the following image

P.S。

您可以运行plt.style.available打印可用样式列表,并享受这些样式。

参考

  1. 有关如何使用样式或撰写自定义样式等详细说明,请参阅here ...

  2. 有人制作了webpage,显示了所有预定义样式的显示效果。太棒了!

相关问题