matplotlib gridspec多个绘图和不同类型的图

2024-10-01 13:43:54 发布

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

How does it look

起初,我开发了这段代码,只用于饼图。工作代码如下。你知道吗

#!/usr/bin/python2.7
#coding=utf8
import os
import matplotlib as mpl
#mpl.use('Agg')
#import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import numpy as np



fig=plt.figure(figsize=(12,12))
graph_grid=GridSpec(1,3)


datas=[[(u'hangup', 480L), (u'invalid', 46L), (u'one', 1235L), (u'repeat', 153L), (u'three', 987L), (u'two', 2379L), (u'wait', 810L)],
[(u'hangBut', 2L), (u'gotoButik', 113L), (u'goBackfrom', 29L), (u'fromIM2Hot', 398L), (u'choice3_to', 1L), (u'choice2_to', 1L)],
[(0L, 5L), (1L, 6L), (2L, 9L), (9L, 419L), (10L, 609L), (11L, 685L), (12L, 694L), (13L, 639L), (14L, 611L), (15L, 566L), (16L, 523L), (17L, 484L), (18L, 327L), (19L, 253L), (20L, 155L), (21L, 61L), (22L, 33L), (23L, 11L)]]

counter=0
for ds in datas:

    labels=[ k[0] for k in ds]
    vals=[ k[1] for k  in ds]
    ziplists=zip(vals,labels)
    ziplists=sorted(ziplists,reverse=True)
    vals, labels = zip(*ziplists)
    total=sum(vals)
    plt.subplot(graph_grid[0,counter], aspect=1)
    #print len(labels)
    #print len(vals)
    print()
    plt.title("title")
    if counter <= 1:
       piechart=plt.pie(vals, autopct=lambda(p): '{:.0f}'.format(p * total / 100), shadow=True,pctdistance=1.2)
       plt.legend(piechart[0], labels, loc="lower right",  prop={'size': 6}, bbox_to_anchor=(0.1, 0.04),)
    elif counter == 2:
        ypos=np.arange(len(labels))
        print ypos
        print len(vals)
        plt.bar(ypos,vals,color='red', width=0.3 )

        plt.xticks(ypos,vals)
        plt.xlabel(u'hours')
        plt.ylabel(u'count')
    counter+=1

fig.tight_layout()
fig.set_size_inches(w=11, h=7)

plt.show()

看上去不错。基本上。但有些数据在柱状图中看起来更好。说-做。 遗憾的是,条形图画得太窄了,我几乎无法改变它的大小。 一些疯狂的宽度值,比如witdth=1000做了一些工作,但图形看起来仍然很糟糕。问题出在哪里?如何修复?你知道吗


Tags: toimportforlabelslenmatplotlibascounter
1条回答
网友
1楼 · 发布于 2024-10-01 13:43:54

问题是您将条形图的纵横比设置为1,与饼图相同。如果删除此项,条形图将变得可读。你知道吗

我可能会将plt.subplot(...)放在if语句中,以便您可以控制何时设置纵横比:

if counter <= 1:
    plt.subplot(graph_grid[0,counter], aspect=1)
    # pie charts here

elif counter == 2:
    plt.subplot(graph_grid[0,counter])
    # bar chart here

这将显示以下图像(您可能需要旋转条形图上的x轴记号以使其看起来更漂亮):

enter image description here

相关问题 更多 >