Python 如何使用matplotlib在一张图表中绘制多个水平条

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15201386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:29:51  来源:igfitidea点击:

How to plot multiple horizontal bars in one chart with matplotlib

pythonmatplotlibplotbar-chart

提问by clstaudt

Can you help me figure out how to draw this kind of plot with matplotlib?

你能帮我弄清楚如何用 matplotlib 绘制这种图吗?

I have a pandas data frame object representing the table:

我有一个表示表的熊猫数据框对象:

Graph       n           m
<string>    <int>      <int>

I want to visualize the size of nand mfor each Graph: A horizontal bar chart where for each row, there is a label containing the Graphname to the left of the y-axis; to the right of the y-axis, there are two thin horizontal bars directly below each other, whose length represents nand m. It should be clear to see that both thin bars belong to the row labelled with the graph name.

我希望显示的大小nm每个Graph:其中对于每个行中,有包含一个标签的水平条形图Graph的名字到y轴的左侧; 在 y 轴的右侧,有两个直接位于彼此下方的细水平条,其长度表示nm。应该清楚地看到,两条细条都属于标有图形名称的行。

This is the code I have written so far:

这是我到目前为止编写的代码:

fig = plt.figure()
ax = gca()
ax.set_xscale("log")
labels = graphInfo["Graph"]
nData = graphInfo["n"]
mData = graphInfo["m"]

xlocations = range(len(mData))
barh(xlocations, mData)
barh(xlocations, nData)

title("Graphs")
gca().get_xaxis().tick_bottom()
gca().get_yaxis().tick_left()

plt.show()

采纳答案by Joe Kington

It sounds like you want something very similar to this example: http://matplotlib.org/examples/api/barchart_demo.html

听起来你想要一些与这个例子非常相似的东西:http: //matplotlib.org/examples/api/barchart_demo.html

As a start:

作为开始:

import pandas
import matplotlib.pyplot as plt
import numpy as np

df = pandas.DataFrame(dict(graph=['Item one', 'Item two', 'Item three'],
                           n=[3, 5, 2], m=[6, 1, 3])) 

ind = np.arange(len(df))
width = 0.4

fig, ax = plt.subplots()
ax.barh(ind, df.n, width, color='red', label='N')
ax.barh(ind + width, df.m, width, color='green', label='M')

ax.set(yticks=ind + width, yticklabels=df.graph, ylim=[2*width - 1, len(df)])
ax.legend()

plt.show()

enter image description here

在此处输入图片说明

回答by Taras Alenin

The question and answers are a bit old now. Based on the documentationthis is much simpler now.

问题和答案现在有点老了。根据文档,这现在要简单得多。

>>> speed = [0.1, 17.5, 40, 48, 52, 69, 88]
>>> lifespan = [2, 8, 70, 1.5, 25, 12, 28]
>>> index = ['snail', 'pig', 'elephant',
...          'rabbit', 'giraffe', 'coyote', 'horse']
>>> df = pd.DataFrame({'speed': speed,
...                    'lifespan': lifespan}, index=index)
>>> ax = df.plot.barh()

enter image description here

在此处输入图片说明