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

cls*_*udt 6 python plot matplotlib bar-chart

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

我有一个表示该表的pandas数据框对象:

Graph       n           m
<string>    <int>      <int>
Run Code Online (Sandbox Code Playgroud)

我想要想象每个的大小n和m每个的大小Graph:一个水平条形图,每行,有一个标签,包含Graphy轴左边的名称; 在y轴的右侧,有两个直接在彼此下方的细水平条,其长度代表n和m.应该清楚地看到两个细条都属于用图形名称标记的行.

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

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()
Run Code Online (Sandbox Code Playgroud)

Joe*_*ton 13

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

作为开始:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Tar*_*nin 10

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

>>> 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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • 您知道如何向此类图表添加标签吗?我的意思是每种动物的“速度”和“寿命”的具体值? (2认同)