如何使用matplotlib在一个图表中绘制多个水平条 [英] How to plot multiple horizontal bars in one chart with matplotlib

查看:190
本文介绍了如何使用matplotlib在一个图表中绘制多个水平条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我有一个代表表格的pandas数据框对象:

I have a pandas data frame object representing the table:

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

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

I want to visualize the size of n and m for each Graph: A horizontal bar chart where for each row, there is a label containing the Graph name 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 n and m. It should be clear to see that both thin bars belong to the row labelled with the graph name.

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

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

推荐答案

听起来您想要的东西与此示例非常相似: http://matplotlib.org/examples/api/barchart_demo.html

It sounds like you want something very similar to this example: 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()

这篇关于如何使用matplotlib在一个图表中绘制多个水平条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆