【问题标题】:How to plot different dataframe data in one figure?如何在一个图中绘制不同的数据框数据?
【发布时间】:2019-11-01 03:45:00
【问题描述】:

我需要一些指导来绘制:

  1. df1 数据的散点图:时间 vs y 使用 z 列的色调
  2. 折线图 df2 数据:时间与 y
  3. y=c 处的一行(c 是常数)

df1 和 df2 中的 y 数据不同,但它们在同一范围内。

我不知道从哪里开始。任何指导表示赞赏。

更多解释。这里展示了一部分数据。我要绘图:

  1. 时间与 CO2 的散点图
  2. 根据小时数据查找 CO2 的年滚动平均值(从 2016 年 1 月 1 日到 2019 年 9 月 30 日。所以第一个平均值将从“01/01/2016 00”到“12/31/2016 23”和第二个平均值将从“01/01/2016 01”到“01/01/2017 00”)(如下图中的趋势)
  3. 找到所有数据的最大值并通过绘图上的一条线(如下面的直线)

样本数据

data = {'Date':['0     01/14/2016 00', '01/14/2016 01','01/14/2016 02','01/14/2016 03','01/14/2016 04','01/14/2016 05','01/14/2016 06','01/14/2016 07','01/14/2016 08','01/14/2016 09','01/14/2016 10','01/14/2016 11','01/14/2016 12','01/14/2016 13','01/14/2016 14','01/14/2016 15','01/14/2016 16','01/14/2016 17','01/14/2016 18','01/14/2016 19'],
        'CO2':[2415.9,2416.5,2429.8,2421.5,2422.2,2428.3,2389.1,2343.2,2444.,2424.8,2429.6,2414.7,2434.9,2420.6,2420.5,2397.1,2415.6,2417.4,2373.2,2367.9],
        'Year':[2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016,2016]} 

# Create DataFrame 
df = pd.DataFrame(data)

# DataFrame view
                Date     CO2  Year
 0     01/14/2016 00  2415.9  2016
       01/14/2016 01  2416.5  2016
       01/14/2016 02  2429.8  2016
       01/14/2016 03  2421.5  2016
       01/14/2016 04  2422.2  2016

【问题讨论】:

标签: python matplotlib seaborn


【解决方案1】:

使用matplotlib.pyplot:

  • plt.hlines在常量处添加一条水平线
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# with synthetic data
np.random.seed(365)
data = {'CO2': [np.random.randint(2000, 2500) for _ in range(783)],
        'Date': pd.bdate_range(start='1/1/2016', end='1/1/2019').tolist()}

# create the dataframe:
df = pd.DataFrame(data)

# verify Date is in datetime format
df['Date'] = pd.to_datetime(df['Date'])

# set Date as index so .rolling can be used
df.set_index('Date', inplace=True)

# add rolling mean
df['rolling'] = df['CO2'].rolling('365D').mean()

# plot the data
plt.figure(figsize=(8, 8))
plt.scatter(x=df.index, y='CO2', data=df, label='data')
plt.plot(df.index, 'rolling', data=df, color='black', label='365 day rolling mean')
plt.hlines(max(df['CO2']), xmin=min(df.index), xmax=max(df.index), color='red', linestyles='dashed', label='Max')
plt.hlines(np.mean(df['CO2']), xmin=min(df.index), xmax=max(df.index), color='green', linestyles='dashed', label='Mean')
plt.xticks(rotation='45')
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()

使用合成数据绘图:

来自操作的数据中的日期格式问题:

  • 使用正则表达式修复Date
  • 将修复Date的代码放在df['Date'] = pd.to_datetime(df['Date'])之前
import re

# your data
                Date     CO2  Year
 0     01/14/2016 00  2415.9  2016
       01/14/2016 01  2416.5  2016
       01/14/2016 02  2429.8  2016
       01/14/2016 03  2421.5  2016
       01/14/2016 04  2422.2  2016

df['Date'] = df['Date'].apply(lambda x: (re.findall(r'\d{2}/\d{2}/\d{4}', x)[0]))

# fixed Date column
       Date     CO2  Year
 01/14/2016  2415.9  2016
 01/14/2016  2416.5  2016
 01/14/2016  2429.8  2016
 01/14/2016  2421.5  2016
 01/14/2016  2422.2  2016

【讨论】:

  • 这太棒了! .rolling('365D').mean() 是否也适用于我的数据? 0 01/14/2016 00, 01/14/2016 01,01/14/2016 02 -------------------- 如您所见,一些数据丢失,一天我可能有 24 个数据,而另一天我可能有 10 个数据,我们甚至可能会丢失一些数据。它如何移动数据?
  • @PouyanEbrahimi 不,您必须将日期固定为实际的日期时间格式。你从(csv,txt)导入什么数据?请将前 5 行数据粘贴到您的问题中,因为它们出现在文件中。根据Date 数据,数据似乎没有正确导入。
  • @PouyanEbrahimi 我在底部添加了一行代码来修复您的Date
【解决方案2】:

您可以使用双轴图表。理想情况下,它看起来与您的相同,因为两个轴的比例相同。可以直接使用 pandas 数据框进行绘图

import matplotlib.pyplot as plt
import pandas as pd

# create a color map for the z column
color_map = {'z_val1':'red', 'z_val2':'blue', 'z_val3':'green', 'z_val4':'yellow'}

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx() #second axis within the first

# define scatter plot
df1.plot.scatter(x = 'date',
                 y = 'CO2',
                 ax = ax1,
                 c = df['z'].apply(lambda x:color_map[x]))

# define line plot
df2.plot.line(x = 'date',
         y = 'MA_CO2', #moving average in dataframe 2
         ax = ax2)


# plot the horizontal line at y = c (constant value)
ax1.axhline(y = c, color='r', linestyle='-')

# to fit the chart properly
plt.tight_layout()

【讨论】:

    猜你喜欢
    • 2019-06-12
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 2021-07-25
    相关资源
    最近更新 更多