Matplotlib:绘制楔形分解成条形的饼图

2024-09-30 10:40:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个饼图(示例),下面是fracs = [10, 20, 50, 30]。用matplotlib绘制这个没有问题。如何将第一个楔子的分解成6和{}?理想情况下,我需要第二个楔子,将20分解成{},37。这将显示为一个条形图,靠近特定的楔子或饼图(这将使它成为一个饼状饼图,类似于Excel中的饼图)。在


Tags: 示例matplotlib绘制情况excel条形图理想分解成
3条回答

这里有一种方法(可能不是最好的……)。我修改了找到的一些代码here, on the matplotlib site来生成一个little_pie函数,它将在任意位置绘制小饼图。在

from pylab import *
import math
import numpy as np

def little_pie(breakdown,location,size):
    breakdown = [0] + list(np.cumsum(breakdown)* 1.0 / sum(breakdown))
    for i in xrange(len(breakdown)-1):
        x = [0] + np.cos(np.linspace(2 * math.pi * breakdown[i], 2 * math.pi *    
                          breakdown[i+1], 20)).tolist()
        y = [0] + np.sin(np.linspace(2 * math.pi * breakdown[i], 2 * math.pi * 
                          breakdown[i+1], 20)).tolist()
        xy = zip(x,y)
        scatter( location[0], location[1], marker=(xy,0), s=size, facecolor=
               ['gold','yellow', 'orange', 'red','purple','indigo','violet'][i%7])

figure(1, figsize=(6,6))

little_pie([10,3,7],(1,1),600)
little_pie([10,27,4,8,4,5,6,17,33],(-1,1),800)

fracs = [10, 8, 7, 10]
explode=(0, 0, 0.1, 0)
pie(fracs, explode=explode, autopct='%1.1f%%')
show()

enter image description here

我找不到解决方法,所以我自己破解了。我在matplotlib.patches补丁程序模块。这允许您在同一图形中的不同轴之间绘制线。下面将在左侧创建饼图,在右侧创建堆积条形图:

import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch
import numpy as np
import math

# style choice
plt.style.use('fivethirtyeight')

# make figure and assign axis objects
fig = plt.figure(figsize=(15,7.5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

# pie chart parameters
ratios = [.4, .56, .04]
labels = ['Approve', 'Disapprove', 'Undecided']
explode=[0.1,0,0]
# rotate so that first wedge is split by the x-axis
angle = -180*ratios[0]
ax1.pie(ratios, autopct='%1.1f%%', startangle=angle,
        labels=labels,explode=explode )

# bar chart parameters

xpos = 0
bottom = 0
ratios = [.33, .54, .07, .06]
width = .2
colors = ['y','m','#99ff99','#ffcc99']

for j in range(len(ratios)):
    height = ratios[j]
    ax2.bar(xpos, height, width, bottom=bottom, color=colors[j])
    ypos = bottom + ax2.patches[j].get_height()/2
    bottom += height
    ax2.text(xpos,ypos, "%d%%" %
        (ax2.patches[j].get_height()*100), ha='center')

plt.title('Gender of approvers')
plt.legend(('Women', 'Men', 'Gender Neutral', 'Alien'))
plt.axis('off')
plt.xlim(-2.5*width, 2.5*width)

然后添加两条线,分别将饼图的第一个楔块与堆积条形图的顶部和底部连接起来:

^{pr2}$

情节如下: Bar in pie example

相关问题 更多 >

    热门问题