如何使用pandas中不同数据帧的列并排绘制两个条形图

2024-06-16 09:37:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用matplotlib/seaborn并排绘制两个条形图,用于两个国家的新冠肺炎确诊病例:意大利和印度进行比较。然而,在尝试了许多方法之后,我没有解决这个问题。这两个国家的确诊病例来自两个不同的数据框架

Data source

我想在x轴上绘制“日期”列,在y轴上绘制“确诊病例数”。
附加我的代码的图像以供参考。
附言:我对数据可视化和熊猫也不熟悉

 import pandas as pd
 import numpy as np
 import matplotlib.pyplot as plt
 import seaborn as sns
 df = pd.read_csv('https://raw.githubusercontent.com/datasets/covid- 
 19/master/data/countries-aggregated.csv', parse_dates = ['Date'])
 df.head(5)

 ind_cnfd = df[['Date', 'Country', 'Confirmed']]
 ind_cnfd = ind_cnfd[ind_cnfd['Country']=='India']
 italy_cnfd = df[['Date', 'Country', 'Confirmed']]
 italy_cnfd = italy_cnfd[italy_cnfd['Country'] == 'Italy']

这种类型的预期输出: x轴上有日期,y轴上有确诊病例 image


Tags: 数据importdfdatematplotlibas绘制seaborn
1条回答
网友
1楼 · 发布于 2024-06-16 09:37:46

下面是一个使用matplotlib与seaborn组合的示例。通过查看matplotlib/seaborn文档,您可以随意使用轴设置、间距等。请注意,如果您想从笔记本中运行这些代码,我只执行了import matplotlib.pyplot as plt。顺便说一下,我没有用seaborn

您可以选择使用以下行以基于日志的y比例显示确诊病例:plt.yscale('log')

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

df = pd.read_csv('https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv',
    parse_dates = ['Date'])

# select the Date, Country, Confirmed features from country, with reset of index
ind_cnfd = df[df.Country == 'India']
ind_cnfd = ind_cnfd[['Date', 'Confirmed']].reset_index(drop = True)
ind_cnfd = ind_cnfd.rename(columns = {'Confirmed': 'Confirmed Cases in India'})

italy_cnfd = df[df.Country == 'Italy']
italy_cnfd = italy_cnfd[['Date', 'Confirmed']].reset_index(drop = True)
italy_cnfd = italy_cnfd.rename(columns = {'Confirmed': 'Confirmed Cases in Italy'})

# combine dataframes together, turn the date column into the index
df_cnfd = pd.concat([ind_cnfd.drop(columns = 'Date'), italy_cnfd], axis = 1)
df_cnfd['Date'] = df_cnfd['Date'].dt.date
df_cnfd.set_index('Date', inplace=True)

# make a grouped bar plot time series
ax = df_cnfd.plot.bar()

# show every other tick label
for label in ax.xaxis.get_ticklabels()[::2]:
    label.set_visible(False)

# add titles, axis labels
plt.suptitle("Confirmed COVID-19 Cases over Time", fontsize = 15)
plt.xlabel("Dates")
plt.ylabel("Number of Confirmed Cases")
plt.tight_layout()
# plt.yscale('log')

plt.show()

enter image description here

相关问题 更多 >