0

I am plotting a bar graph from a Pandas DataFrame in Jupyter Notebook and for some reason I am unable to change the grey background of the plot to white.

df = pd.DataFrame({
    'Name': ['John', 'Sammy', 'Joe'],
    'Age': [45, 38, 90],
    'Height(in cm)': [150, 180, 160]
})
  
# plotting graph
df.plot(x="Name", y=["Age", "Height(in cm)"], kind="bar")

The code above plots the following: Bar plot with Grey Background

I've tried plt.figure(facecolor='white') and plt.rcParams["axes.facecolor"] = "white", neither of which changed the background of the plot.

I have also tried adding

ax = plt.axes()
ax.set_facecolor("white")

before plt.show() but no success.

1 Answer 1

2

To change the background outside of the plot, changing the style should be the easiest way:

plt.style.use('default')

The list of styles: https://matplotlib.org/stable/gallery/style_sheets/style_sheets_reference.html

If you want to change the background inside the plot, you are doing the right things in the wrong order, and you have to asign your plot to the ax:

df = pd.DataFrame({
    'Name': ['John', 'Sammy', 'Joe'],
    'Age': [45, 38, 90],
    'Height(in cm)': [150, 180, 160]
})

# plotting graph

ax = plt.axes()
ax.set_facecolor("white")
df.plot(x="Name", y=["Age", "Height(in cm)"], kind="bar", ax=ax)

So a complete solution should be:

df = pd.DataFrame({
    'Name': ['John', 'Sammy', 'Joe'],
    'Age': [45, 38, 90],
    'Height(in cm)': [150, 180, 160]
})

# plotting graph

plt.style.use('default')

ax = plt.axes()
ax.set_facecolor("white")
df.plot(x="Name", y=["Age", "Height(in cm)"], kind="bar", ax=ax)

You can modify the style you are using by adding:

# plotting graph

plt.style.use('fivethirtyeight')

fig, ax = plt.subplots()
fig.patch.set_facecolor('xkcd:white') # This changes the grey to white
ax.set_facecolor("white")
df.plot(x="Name", y=["Age", "Height(in cm)"], kind="bar", ax=ax)

I hope that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Amazing, thank you! I was using the fivethirtyeight style. Do you know of any way I could keep using it but only with its background color modified? It has a lot of other features I require.
No worries. You can use: fig, ax = plt.subplots() fig.patch.set_facecolor('xkcd:white'). I've edited the answer to include that at the bottom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.