gpt4 book ai didi

使用子图的 Pandas 条形图

转载 作者:行者123 更新时间:2023-12-02 06:37:40 30 4
gpt4 key购买 nike

我正在使用 pandas 来创建条形图。这是一个例子:

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

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

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

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

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... 未注释的输出。

Plot with the lines 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');

那么你可以看看this

关于使用子图的 Pandas 条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50863575/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com