Uninvited Guest
Uninvited Guest

Reputation: 1915

change a charts border area color

Is it possible to set the area outside of the chart to the black color? I have the chart area set to black but the outside area has a grey color. Can i change this to black and maybe set the axis color to white if they are not visible?

I make a chart like this:

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()

Upvotes: 6

Views: 8540

Answers (2)

jdhao
jdhao

Reputation: 28449

Another solution which is less flexible than @Ffisegydd's answer but easier is that you can use style 'dark_background' predefined in pyplot module to achieve a similar effect. The code is:

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 above code produces the following image.

P.S.

You can run plt.style.available to print a list of available styles, and have fun with these styles.

References

  1. See here for a detailed explanations on how to use styles or compose custom styles and more...

  2. Someone has made a webpage which shows the display effect of all predefined styles. Pretty awesome!

Upvotes: 6

Ffisegydd
Ffisegydd

Reputation: 53698

The border you're referring to can be modified using the facecolor attribute. The easiest way to modify this with your code would be to use:

plt.gcf().set_facecolor('white') # Or any color

Alternatively you can set it using a keyword argument if you create the figure manually.

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

Upvotes: 5

Related Questions