您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用Python库绘制共享相同y轴的两个水平条形图

5b51 2022/1/14 8:22:49 python 字数 3868 阅读 568 来源 www.jb51.cc/python

我想绘制两个共享相同y轴的水平条形图.例如,以下问题显示了如何在R中实现此目的: Two horizontal bar charts with shared axis in ggplot2 (similar to population pyramid) 如何用Python创建类似的情节? 上面问题的情节如下: 以下是上图中使用的状态列表(y轴): ["AK", "TX", "CA", "MT",

概述

Two horizontal bar charts with shared axis in ggplot2 (similar to population pyramid)

如何用Python创建类似的情节?

上面问题的情节如下:

以下是上图中使用的状态列表(y轴):

["AK","TX","CA","MT","NM","AZ","NV","CO","OR","WY","MI","MN","UT","ID","KS","NE","SD","WA","ND","OK"]

以下是每个州的销售人员数量列表:

[20,30,40,10,15,35,18,25,22,7,12,3,4,5,8,14,28,24,32]

销售数字可以是随机的.

例如:

import matplotlib.pyplot as plt

y = range(20)
x1 = range(20)
x2 = range(0,200,10)

fig,axes = plt.subplots(ncols=2,sharey=True)
axes[0].barh(y,x1,align='center',color='gray')
axes[1].barh(y,x2,color='gray')
axes[0].invert_xaxis()
plt.show()

如果你想更精确地重现你链接到的问题中显示的例子(我将离开灰色背景和白色网格,但如果你喜欢它们,那么很容易添加):

import numpy as np
import matplotlib.pyplot as plt

# Data
states = ["AK","OK"]
staff = np.array([20,32])
sales = staff * (20 + 10 * np.random.random(staff.size))

# Sort by number of sales staff
idx = staff.argsort()
states,staff,sales = [np.take(x,idx) for x in [states,sales]]

y = np.arange(sales.size)

fig,color='gray',zorder=10)
axes[0].set(title='Number of sales staff')
axes[1].barh(y,sales,zorder=10)
axes[1].set(title='Sales (x $1000)')

axes[0].invert_xaxis()
axes[0].set(yticks=y,yticklabels=states)
axes[0].yaxis.tick_right()

for ax in axes.flat:
    ax.margins(0.03)
    ax.grid(True)

fig.tight_layout()
fig.subplots_adjust(wspace=0.09)
plt.show()

一个警告.我没有真正正确对齐y-tick-labels.有可能做到这一点,但它比你想象的更痛苦.因此,如果你真的想要y-tick-labels总是完美地居中于图的中间,那么最简单的方法是以不同的方式绘制它们.而不是axis [0] .set(yticks = y,yticklabels = states),你会做类似的事情:

axes[0].set(yticks=y,yticklabels=[])
for yloc,state in zip(y,states):
    axes[0].annotate(state,(0.5,yloc),xycoords=('figure fraction','data'),ha='center',va='center')

总结

以上是编程之家为你收集整理的使用Python库绘制共享相同y轴的两个水平条形图全部内容,希望文章能够帮你解决使用Python库绘制共享相同y轴的两个水平条形图所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶