如何用matplotlib绘制多个水平条形图
你能帮我弄明白怎么用matplotlib画这种图吗?
我有一个pandas数据框,里面代表了一个表格:
Graph n m
<string> <int> <int>
我想要展示每个Graph
的n
和m
的大小:我想画一个横向的条形图。在每一行的左边,y轴旁边有一个标签,显示Graph
的名字;在y轴的右边,有两条细细的横条,直接上下排列,它们的长度分别代表n
和m
。这样一来,大家就能很清楚地看到这两条细条是属于哪个Graph
的。
这是我到目前为止写的代码:
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()
2 个回答
18
这个问题和回答有点旧了。根据官方文档,现在做起来简单多了。
>>> 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()
32
听起来你想要的东西和这个例子很像: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()