Reputation: 29610
I have the following subplots with pie charts, output by the code below.
I want to shade in a different color the background of the odd-numbered subplots (only the middle one in the image above), but I haven't been able make it work.
I looked at a few places and from a few answers to this question I tried both ax.set_facecolor('red')
and ax.patch.set_facecolor('red')
, none of which resulted in the alternative shading/coloring pattern I'm looking for.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
n = 3
nums_df = pd.DataFrame([np.random.randint(1, 20, size=5) for _ in xrange(n)])
row_labels = ["row {:d}".format(i) for i in xrange(n)]
nums_df.index = row_labels
# create a figure with n subplots
fig, axes = plt.subplots(1, n)
# create pie charts
for i, ax in enumerate(axes):
ax.pie(nums_df.loc[row_labels[i]], labels=nums_df.loc[row_labels[i]])
ax.axis("equal")
if i%2 == 1:
ax.set_facecolor('red')
# ax.patch.set_facecolor('red')
plt.show()
Upvotes: 1
Views: 2603
Reputation: 339430
By default the complete axes of a pie plot is "off". You can set it on, use the frame
argument.
ax.pie(..., frame=True)
This produces ticks and ticklabels on the axes, hence, it might be better to set it on externally,
ax.pie(..., frame=False)
ax.set_frame_on(True)
In addition you probably want to set the spines off,
for _, spine in ax.spines.items():
spine.set_visible(False)
or, in a single line
plt.setp(ax.spines.values(),visible=False)
Finally, for the ticklabels not to exceed the axes area, one may fix the axis range, e.g. ax.axis([-1,1,-1,1])
and use a smaller pie radius, e.g. radius=.27
.
Complete code for reproduction
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
n = 3
nums_df = pd.DataFrame([np.random.randint(1, 20, size=5) for _ in xrange(n)])
row_labels = ["row {:d}".format(i) for i in xrange(n)]
nums_df.index = row_labels
fig, axes = plt.subplots(1, n)
for i, ax in enumerate(axes):
ax.pie(nums_df.loc[row_labels[i]], labels=nums_df.loc[row_labels[i]], frame=False, radius=0.27)
ax.set_frame_on(True)
ax.axis("equal")
ax.axis([-1,1,-1,1])
plt.setp(ax.spines.values(),visible=False)
if i%2 == 1:
ax.set_facecolor('red')
plt.show()
Upvotes: 2