简体   繁体   English

更改特定子图的背景颜色(饼图外部)

[英]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. 我看了几个地方,从这个问题的几个答案中,我都尝试了ax.set_facecolor('red')ax.patch.set_facecolor('red') ,但没有一个导致替代的阴影/着色模式。我在寻找。

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". 默认情况下,饼图的完整轴为“ off”。 You can set it on, use the frame argument. 您可以使用frame参数将其设置为on。

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 . 最后,为使勾号标签不超过轴区域,可以固定轴范围,例如ax.axis([-1,1,-1,1])并使用较小的圆饼半径,例如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() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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