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:
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.
CodePudding user response:
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.