【问题标题】:Python: Using Pandas to plot more than one series in each subplotPython:使用 Pandas 在每个子图中绘制多个系列
【发布时间】:2015-07-30 15:18:40
【问题描述】:

使用 python,我创建了一个包含四列(日期、df1、df2、df3)的 pandas 数据框。 “日期”系列是数据框的索引。

我正在尝试创建两个子图(阅读:两个堆叠图),它们共享“日期”系列作为 x 轴。

我想在第一个子图上绘制系列 1 和系列 2,使用颜色:黑色和蓝色。

在第二个子图中,我想绘制 series3,使用颜色:红色。

有人知道我如何使用 pandas 或 matplotlib 来做这件事吗?

提前致谢!

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

file1 = "LNQ2014LNV2014"
file2 = "LNV2014LNZ2014"
file3 = "LNQ2014LNV2014LNV2014LNZ2014"

df1 = pd.read_csv("%s.csv" % (file1), index_col = 0)
df1 = df1.drop(df1.columns[[0,1,2,4,5]], axis = 1)
df1.columns = ["%s" % file1]

df2 = pd.read_csv("%s.csv" % (file2), index_col = 0)
df2 = df2.drop(df2.columns[[0,1,2,4,5]], axis = 1)
df2.columns = ["%s" % file2]

df3 = pd.read_csv("%s.csv" % (file3), index_col = 0)
df3 = df3.drop(df3.columns[[0,1,2,4,5]], axis = 1)
df3.columns = ["%s" % file3]

dfresult = pd.concat([df1, df2, df3], axis = 1, join = "inner")

plt.subplot(211)
plt.plot(df1, color = "black")
plt.plot(df2, color = "blue")
plt.subplot(212)
plt.plot(df3, color = "red")

plt.show()

【问题讨论】:

    标签: python pandas matplotlib colors subplot


    【解决方案1】:

    你会想要使用 subplot 函数。这会创建 2 个垂直堆叠的图,就像您提到的那样:

    from matplotlib import pylab as pl
    
    pl.subplot(211)
    pl.plot(date, series1, color='black')
    pl.plot(date, series2, color='blue')
    pl.subplot(212)
    pl.plot(date, series3, color='red')
    pl.show()
    

    【讨论】:

    • 感谢您发布此问题的答案!在 Stack Overflow 上只回答 are discouraged 的代码,因为没有上下文的代码转储无法解释解决方案如何或为什么会起作用,使得原始发布者(或任何未来的读者)无法理解其背后的逻辑。请编辑您的问题并包含对您的代码的解释,以便其他人可以从您的回答中受益。
    猜你喜欢
    • 2021-01-14
    • 2020-08-04
    • 2021-09-11
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多