gpt4 book ai didi

python - 同一图上的条形图/线图,但条形图前面的轴和线图不同

转载 作者:行者123 更新时间:2023-12-04 21:09:18 27 4
gpt4 key购买 nike

我正在使用 Pandas 来绘制一些数据。

如果我绘制这个:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'a': [100, 200, 150, 175],
'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
df['b'].plot(kind='bar', color='y')
df['a'].plot(kind='line', marker='d')

一切都很好。

GoodGraph

如果我在辅助轴上绘制条形轴,条形图将位于线图的前面,阻碍线被查看,就像这样。

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'a': [100, 200, 150, 175],
'b': [430, 30, 20, 10]})
fig, ax1 = plt.subplots(figsize=(15, 10))
df['b'].plot(kind='bar', color='y', secondary_y=True)
df['a'].plot(kind='line', marker='d')

SadGraph

如何制作条形图/线图,其中...
  • 使用 Pandas /matplotlib
  • 条形图位于辅助轴上,折线图位于主轴上
  • 线图位于条形图的前面
  • 最佳答案

    你可以把线放在主轴上。

    import pandas as pd
    import matplotlib.pyplot as plt

    df = pd.DataFrame({'a': [100, 200, 150, 175],
    'b': [430, 30, 20, 10]})
    fig, ax1 = plt.subplots(figsize=(15, 10))
    df['b'].plot(kind='bar', color='y')
    df['a'].plot(kind='line', marker='d', secondary_y=True)

    enter image description here

    或者,创建两个轴 ax1ax2 twinx() .
    import pandas as pd
    import matplotlib.pyplot as plt

    df = pd.DataFrame({'a': [100, 200, 150, 175],
    'b': [430, 30, 20, 10]})
    fig, ax1 = plt.subplots(figsize=(15, 10))
    ax2 = ax1.twinx()
    df['b'].plot(kind='bar', color='y', ax=ax1)
    df['a'].plot(kind='line', marker='d', ax=ax2)
    ax1.yaxis.tick_right()
    ax2.yaxis.tick_left()

    enter image description here

    关于python - 同一图上的条形图/线图,但条形图前面的轴和线图不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38131697/

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