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

2024-10-04 01:27:55 发布

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

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

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

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

我想可视化每个nm的大小:一个水平条形图,其中每一行的y轴左侧有一个包含Graph名称的标签;y轴右侧有两个彼此正下方的细水平条,其长度表示nm。应该清楚地看到,这两个细条都属于用图形名称标记的行。

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

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()

Tags: 名称getmatplotlib水平pltaxgraphint
2条回答

听起来你想要的东西和这个例子非常相似: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()

enter image description here

现在的问题和答案有点陈旧了。Based on the documentation这现在简单多了。

>>> 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

相关问题 更多 >