使用子图的 pandas 条形图 [英] Pandas Bar Plot using Subplots

查看:66
本文介绍了使用子图的 pandas 条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用熊猫来创建条形图.下面是一个例子:

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

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

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

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?

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

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.

再次尝试,但做了一些修改.

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

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

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.

推荐答案

可以从这里开始玩:

%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');

那你可以看看这个

这篇关于使用子图的 pandas 条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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