python - 在同一张图表上将 Pandas DataFrame 绘制为条形图和折线图

标签 python matplotlib charts pandas

我正在尝试绘制一个图表,其中第 1 列和第 2 列数据作为条形,然后为第 3 列数据绘制一条线。

我尝试了以下代码,但这会创建 2 个单独的图表,但我希望所有这些都在一个图表上。

left_2013 = pd.DataFrame({'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],
                     '2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]})

right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]})

right_2014_target = pd.DataFrame({'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],
                                   '2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]})


df_13_14 = pd.merge(left_2013, right_2014, how='outer')
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer')
df_13_14_target[['month','2013_val','2014_val','2014_target_val']].head(12)

plt.figure()
df_13_14_target[['month','2014_target_val']].plot(x='month',linestyle='-', marker='o')
df_13_14_target[['month','2013_val','2014_val']].plot(x='month', kind='bar')

这是我目前得到的

kpi dashboard

最佳答案

DataFrame 绘图方法返回一个 matplotlib AxesSubplotAxesSubplots 列表。 (例如,参见 the docs for plotboxplot。)

然后您可以将相同的轴传递给下一个绘图方法(使用 ax=ax)以在相同的轴上绘制:

ax = df_13_14_target[['month','2014_target_val']].plot(x='month',linestyle='-', marker='o')
df_13_14_target[['month','2013_val','2014_val']].plot(x='month', kind='bar', 
   ax=ax)

import pandas as pd
import matplotlib.pyplot as plt

left_2013 = pd.DataFrame(
    {'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
               'oct', 'nov', 'dec'],
     '2013_val': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 6]})

right_2014 = pd.DataFrame({'month': ['jan', 'feb'], '2014_val': [4, 5]})

right_2014_target = pd.DataFrame(
    {'month': ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
               'oct', 'nov', 'dec'],
     '2014_target_val': [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]})

df_13_14 = pd.merge(left_2013, right_2014, how='outer')
df_13_14_target = pd.merge(df_13_14, right_2014_target, how='outer')

ax = df_13_14_target[['month', '2014_target_val']].plot(
    x='month', linestyle='-', marker='o')
df_13_14_target[['month', '2013_val', '2014_val']].plot(x='month', kind='bar',
                                                        ax=ax)

plt.show()

enter image description here

关于python - 在同一张图表上将 Pandas DataFrame 绘制为条形图和折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23482201/

相关文章:

angular - 如何将 C3 图表添加到 Angular 2+ 项目

python - 在 Heroku 上发送 Django 电子邮件

python - 更新 DRF 中帖子的点赞

python - Matplotlib 没有给出错误,但没有绘制任何内容

matplotlib - 当 DataFrame-Column 缺少值时 PyPlot 会抛出错误

python - Matplotlib 三角形 (plot_trisurf) 颜色和网格

Python minimax函数中的深度复制

Python - 组合两个 json 对象

javascript - Highcharts - 对 Angular 线 X/Y 轴

javascript - 显示条形和线条之间的间隙(差异)