pandas数据框架:以多列和日期时间为索引的seaborn图条 df.plot.bar()

问题描述 投票:0回答:1

我有一个数据框架,有两列这样的(以日期为索引)。

enter image description here

我的目标是像这样用seaborn绘制条形图(用excel)。

enter image description here

我遵循这里的讨论。在这里输入链接描述

我知道,我必须使用熔体.但当我把下面的代码的结果是索引(日期)消失(由数字取代)和数据框架结构改变这样的。

# pd.melt(df, id_vars=['A'], value_vars=['B'])
premier_melt = pd.melt(final_mada_df,id_vars=["Confirmed"],value_vars = ["Recovered"])

enter image description here

我们怎样才能解决这种问题,正确地用seaborn绘制条形图呢?

先谢谢


我把下面的代码按照下面的建议。

# main dataframe 
  df2
       Recovered Confirmed
3/20/20   0          3
3/21/20   0          0
3/22/20   0          0
3/23/20   0          9

df2.stack()

out :

3/20/20  Recovered    0
         Confirmed    3
3/21/20  Recovered    0
         Confirmed    0
3/22/20  Recovered    0
                     ..
5/4/20   Confirmed    0
5/5/20   Recovered    2
         Confirmed    2
5/6/20   Recovered    0
         Confirmed    7
Length: 96, dtype: int64

df2.rename(columns={'level_1':'Status',0:'Values'})

out:

       Recovered Confirmed
3/20/20   0         3
3/21/20   0         0
3/22/20   0         0
3/23/20   0         9
3/24/20   0         5

但当我把下面的代码,有一个错误。

# plot 
ax = sns.barplot(x=df2.index,y='Values',data=df2,hue='Status')

ValueError: Could not interpret input 'Values'
python pandas seaborn
1个回答
2
投票

使用 .stack(),如下图所示。

import pandas as pd
import seaborn as sns
import numpy as np
from datetime import datetime
import matplotlib.pyplot as plt

# optional graph format parameters
plt.rcParams['figure.figsize'] = (16.0, 10.0)
plt.style.use('ggplot')

# data
np.random.seed(365)
data = {'Confirmed': [np.random.randint(10) for _ in range(25)],
        'date': pd.bdate_range(datetime.today(), freq='d', periods=25).tolist()}

# dataframe
df = pd.DataFrame(data)

# add recovered
df['Recovered'] = df['Confirmed'].div(2)

| date                |   Confirmed |   Recovered |
|:--------------------|------------:|------------:|
| 2020-05-12 00:00:00 |           4 |         2   |
| 2020-05-13 00:00:00 |           1 |         0.5 |
| 2020-05-14 00:00:00 |           5 |         2.5 |
| 2020-05-15 00:00:00 |           1 |         0.5 |
| 2020-05-16 00:00:00 |           9 |         4.5 |

# verify datetime format and set index
df.date = pd.to_datetime(df.date)
df.set_index('date', inplace=True)

转换数据

  • 这种转换是必要的,以获得所需的情节从seaborn
df1 = df.stack().reset_index().set_index('date').rename(columns={'level_1': 'Status', 0: 'Values'})

| date                | Status    |   Values |
|:--------------------|:----------|---------:|
| 2020-05-23 00:00:00 | Confirmed |        2 |
| 2020-05-23 00:00:00 | Recovered |        1 |
| 2020-05-24 00:00:00 | Confirmed |        4 |
| 2020-05-24 00:00:00 | Recovered |        2 |
| 2020-05-25 00:00:00 | Confirmed |        1 |

Seaborn情节

  • 格式化X轴刻度线标签需要使用的是 dfdf1. 如上图所示,每个日期都会重复,所以 df1.index.to_series() 将产生一个日期重复的列表。
ax = sns.barplot(x=df1.index, y='Values', data=df1, hue='Status')

# format the x-axis tick labels uses df, not df1
ax.xaxis.set_major_formatter(plt.FixedFormatter(df.index.to_series().dt.strftime("%Y-%m-%d")))

# alternative use the following to format the labels
# _, labels = plt.xticks()
# labels = [label.get_text()[:10] for label in labels]
# ax.xaxis.set_major_formatter(plt.FixedFormatter(labels))

plt.xticks(rotation=90)
plt.show()

或者 df.plot.bar()

  • 生成与上述相同的图形,但没有转换为 df1
  • df 有一个日期时间指数,它被认为是x轴,所有的列都被绘制在y轴上。
ax = df.plot.bar()
ax.xaxis.set_major_formatter(plt.FixedFormatter(df.index.to_series().dt.strftime("%Y-%m-%d")))
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.