简体   繁体   中英

change specific subplot background color (outside of pie chart)

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

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, eg ax.axis([-1,1,-1,1]) and use a smaller pie radius, eg 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() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM