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

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

问题描述

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

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

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

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天全站免登陆