pandas 使用子图的熊猫条形图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50863575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:42:05  来源:igfitidea点击:

Pandas Bar Plot using Subplots

pandasplot

提问by Charanjit Pabla

I am using pandas to create bar plot. Here is an example:

我正在使用Pandas来创建条形图。下面是一个例子:

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
df.plot(kind='bar')

I want to plot two subplots within a figure and have a and b on one bar plot and c and d on another. How do I go about this?

我想在一个图中绘制两个子图,并在一个条形图中有 a 和 b,在另一个条形图中有 c 和 d。我该怎么做?

Further, if I wanted to include the two subplots with another subplot but not created by pandas, how to do that? So a 3x1 figure where two of the subplots are from the data frame using pandas and one without using pandas. Example Plot

此外,如果我想将两个子图与另一个子图一起包含但不是由Pandas创建的,该怎么做?所以一个 3x1 的图,其中两个子图来自使用Pandas的数据框,一个不使用Pandas。 示例图

Taking a second attempt at this but with some modifications.

对此进行第二次尝试,但进行了一些修改。

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
x=[1,2,3,4,5]
y=[1,4,9,16,25]

fig, axes = plt.subplots(figsize=(8,8),nrows=2, ncols=2)
ax1=plt.subplot(2,2,1)
plt.plot(x,y)

#ax2=plt.subplot(2,2,2)
df["b"].plot(ax=axes[0,1], kind='bar', grid=True)
df["c"].plot(ax=axes[1,0], kind='bar', grid=True)
df["d"].plot(ax=axes[1,1], kind='bar', grid=True)

ax1.grid(True)
ax1.set_ylabel('Test')
ax1.set_xlabel('Test2')

#ax2.set_ylabel('Test')

How do I add axes labels for the bar plots in my subplots? Notice I have commented out ax2=plt.subplot(2,2,2) as I was testing this but this erases the bar plot completely and add the labels. Why does it do that and how can I get around this? Below is the output with the ax2... un-commented.

如何为子图中的条形图添加轴标签?请注意,我在测试时已注释掉 ax2=plt.subplot(2,2,2),但这会完全擦除条形图并添加标签。为什么会这样,我该如何解决这个问题?下面是带有 ax2... 未注释的输出。

Plot with the lines un-commented

绘制未注释的线条

回答by rpanai

You can start to play from this:

你可以从这个开始玩:

%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df=pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])

fig, axes = plt.subplots(nrows=1, ncols=2)
df[["a","b"]].plot(ax=axes[0],kind='bar')
df[["c", "d"]].plot(ax=axes[1], kind='bar');

Then you can have a look at this

然后你可以看看这个