gpt4 book ai didi

Python Pandas 并排绘制两个 BARH

转载 作者:太空狗 更新时间:2023-10-29 22:14:58 25 4
gpt4 key购买 nike

我正在尝试制作一个类似这样的情节, enter image description here

左侧图表(带图例的图)源自 df_2,右侧图表源自 df_1

但是,我不能让两个并排的图共享 y 轴。

这是我目前的绘图方式:

df_1[target_cols].plot(kind='barh', x='LABEL', stacked=True, legend=False)
df_2[target_cols].plot(kind='barh', x='LABEL', stacked=True).invert_xaxis()
plt.show()

代码将在两个不同的“ Canvas ”中生成两个图。

  1. 如何让它们并排共享 y 轴?
  2. 如何删除左侧图表(源自 df_2 的图表)在 y 轴上的标签?

最佳答案

您可以使用 plt.subplots(sharey=True) 创建共享子图。然后将数据帧绘制到两个子图中。

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

a = np.random.randint(5,15, size=10)
b = np.random.randint(5,15, size=10)

df = pd.DataFrame({"a":a})
df2 = pd.DataFrame({"b":b})

fig, (ax, ax2) = plt.subplots(ncols=2, sharey=True)

ax.invert_xaxis()
ax.yaxis.tick_right()

df["a"].plot(kind='barh', x='LABEL', legend=False, ax=ax)
df2["b"].plot(kind='barh', x='LABEL',ax=ax2)
plt.show()

enter image description here

关于Python Pandas 并排绘制两个 BARH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44049132/

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