Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

python - How to plot multiple horizontal bars in one chart with 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>

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like you want something very similar to this example: http://matplotlib.org/examples/api/barchart_demo.html

As a start:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...