【问题标题】:How to plot based upon unique column values?如何根据唯一列值进行绘图?
【发布时间】:2020-02-28 23:30:52
【问题描述】:

我是一名初学者,正在学习使用 python 进行数据可视化。 我发现联合国提供的一个非常酷的数据集,其格式如下:

Afghanistan 1975 2127   
Afghanistan 1985 3509   
Afghanistan 1995 1243   
Afghanistan 2005 1327
Albania 1975 4595   
Albania 1985 7880   
Albania 1995 2087   
Albania 2005 4254
etc...

到目前为止,我一直在用这样的语句解析各个国家/地区:

china = data[data.area == 'China']

这对于选择单个国家/地区很好,但现在,我想绘制所有这些国家/地区。我该怎么办? 到目前为止,我已经尝试过了,但不知道如何使它工作:

old_value = data.iloc[0]
for i in len(data):
    if data.iloc[i].area == old_value:
#         add to current set
    else:
#      create new set

任何帮助将不胜感激!

【问题讨论】:

  • 您仍然对这个问题的答案感兴趣吗?你能链接到数据文件吗?

标签: python-3.x pandas matplotlib seaborn


【解决方案1】:

鉴于您的数据

  • 设置导入和数据框
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# plot parameters
plt.style.use('seaborn')
plt.rcParams['figure.figsize'] = (16.0, 10.0)

data = {'country': ['Afghanistan', 'Afghanistan', 'Afghanistan', 'Afghanistan', 'Albania', 'Albania', 'Albania', 'Albania'],
        'year': [1975, 1985, 1995, 2005, 1975, 1985, 1995, 2005],
        'value': [2127, 3509, 1243, 1327, 4595, 7880, 2087, 4254]}

df = pd.DataFrame(data)

       country  year  value
0  Afghanistan  1975   2127
1  Afghanistan  1985   3509
2  Afghanistan  1995   1243
3  Afghanistan  2005   1327
4      Albania  1975   4595
5      Albania  1985   7880
6      Albania  1995   2087
7      Albania  2005   4254

seaborn.barplothue 参数一起使用

p = sns.barplot(x='year', y='value', hue='country', data=df)

横向

p = sns.barplot(x='value', y='year', hue='country', data=df, orient='h')

每个国家/地区的单独图

  • 使用plt.subplot(1, 2, i) 行乘以列应该等于唯一国家/地区的数量,如果有奇数则+1。
max_value = df.value.max() + 100  # + 100 to add padding at the top of the plot; 100 is an arbitrary value and can be removed
for i, country in enumerate(df.country.unique(), 1):  # iterate through each unique country
    data = df[df.country == country]  # filter by country
    plt.subplot(1, 2, i)  # rows, columns, i: plot index beginning at 1
    sns.barplot(x='year', y='value', data=data)
    plt.ylim(0, max_value)  # set y-lim with max of the value column; makes it easier to compare countries
    plt.title(country)

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多