Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python库绘制共享同一y轴的两个水平条形图_Python_Matplotlib_Pandas - Fatal编程技术网

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

使用Python库绘制共享同一y轴的两个水平条形图,python,matplotlib,pandas,Python,Matplotlib,Pandas,我想画两个共享相同y轴的水平条形图。例如,以下问题说明了如何在R中实现这一点: 如何使用Python创建类似的绘图 上述问题的情节如下所示: 以下是上图中使用的状态列表(y轴): 以下是每个州的销售人员数量列表: [20,30,40,10,15,35,18,25,22,7,12,22,3,4,5,8,14,28,24,32] 销售数字可以是随机的。使用我在matplotlib邮件列表中找到的一些信息,我修改了matplotlib水平条形图的一个示例,以制作金字塔图 下面列出的棱锥图功能将并

我想画两个共享相同y轴的水平条形图。例如,以下问题说明了如何在R中实现这一点:

如何使用Python创建类似的绘图

上述问题的情节如下所示:

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

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

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

销售数字可以是随机的。

使用我在matplotlib邮件列表中找到的一些信息,我修改了matplotlib水平条形图的一个示例,以制作金字塔图

下面列出的
棱锥图
功能将并排绘制水平条

def pyramid_plot(ylabels, data_left, xlabel_left, data_right, xlabel_right, fig=None, **kwargs):
    if(fig is None):
        fig = plt.figure()

    y_pos = np.arange(len(ylabels))
    empty_ticks = tuple('' for n in people)

    fig.add_subplot(121)
    plt.barh(y_pos, data_left, **kwargs)
    plt.yticks(y_pos, empty_ticks)
    oldlims = plt.gca().get_xlim()
    plt.axis(xmin=oldlims[1], xmax=oldlims[0])
    plt.xlabel(xlabel_left)

    fig.add_subplot(122)
    plt.barh(y_pos, data_right, **kwargs)
    plt.yticks(y_pos, ylabels)
    plt.xlabel(xlabel_right)

    return fig
金字塔图
功能的使用如下

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

# Example data
people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
performance = 3 + 10 * np.random.rand(len(people))
salary = np.linspace(30,60,len(people))

# Plot the data
pyrfig = plt.figure(1)
pyrfig = pyramid_plot(people, salary, 'Salary (thousands)', performance, 'Performance', pyrfig, align='center', alpha=0.4)
pyrfig.suptitle('Pyramid Plot')
pyrfig.set_figwidth(1.5*pyrfig.get_figheight())
plt.show(pyrfig)

参考资料:


一般来说,如果显示的两个变量的单位不同或范围不同,则需要使用两个具有共享y轴的子图。这与@regdoug的答案类似,但最好明确共享y轴,以确保数据保持对齐(例如,在本例中尝试缩放/平移)

例如:

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, align='center', color='gray')
axes[0].invert_xaxis()
plt.show()

如果您想更精确地再现您链接到的问题中显示的示例(我不使用灰色背景和白色网格,但如果您愿意,它们很容易添加):

一个警告。实际上,我没有正确对齐y记号标签。这是可能的,但这比你想象的更痛苦。因此,如果你真的想要Y-TICK标签,它们总是完美地集中在图中间,那么用不同的方法绘制它们是最容易的。与轴[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')

更改上述条形图上x轴范围/限制的最佳方法是什么?@卡盘轴[0]。轴(xmin=0,xmax=1)轴[1]。轴(xmin=0,xmax=1)
import numpy as np
import matplotlib.pyplot as plt

# Data
states = ["AK", "TX", "CA", "MT", "NM", "AZ", "NV", "CO", "OR", "WY", "MI",
          "MN", "UT", "ID", "KS", "NE", "SD", "WA", "ND", "OK"]
staff = np.array([20, 30, 40, 10, 15, 35, 18, 25, 22, 7, 12, 22, 3, 4, 5, 8,
                  14, 28, 24, 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, staff, sales]]

y = np.arange(sales.size)

fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].barh(y, staff, align='center', color='gray', zorder=10)
axes[0].set(title='Number of sales staff')
axes[1].barh(y, sales, align='center', color='gray', 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()
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')