用Python可视化数据

3

我想在数据集上创建一张柱状图,显示所有时间排名前500首歌曲中拥有最多歌曲的前10位艺术家。我已经得到了结果,但是我不知道该如何将其可视化。我需要用代码生成一个柱状图来展示我得到的输出结果。 我已经导入了pandas、seaborn和matplot,只需要帮助我编写代码。

counts = dict()
for artists in my_data['artist']:
    counts[artists] = counts.get(artists, 0) + 1

def keyfunction(k):
    return counts[k]

plt.figure(figsize = (10, 30))
plt.title("Greatest Artists of All Time")
data = dict()

for key in sorted(counts, key=keyfunction, reverse=True)[:10]:
    print(key, counts[key])

需要制作以下输出的条形图。
Elton John 18
The Beatles 16
Elvis Presley 12
The Jimi Hendrix Experience 12
The Four Tops 10
Muddy Waters 8
Sam Cooke 8
The Clash 8
U2 8
The Isley Brothers 8
2个回答

1
你可以这样做,

import numpy as np
import matplotlib.pyplot as plt

# I assumed your counts is a dictionary
counts = {
    "Elton John": 18,
    "The Beatles": 16,
    "Elvis Presley": 12,
    "The Jimi Hendrix Experience": 12,
    "The Four Tops": 10,
    "Muddy Waters": 8,
    "Sam Cooke": 8,
    "The Clash": 8,
    "U2": 8,
    "The Isley Brothers": 8
}

y_pos = np.arange(len(counts))

# Create bars
plt.bar(y_pos, counts.values())

# Create names on the x-axis
plt.xticks(y_pos, counts.keys())

# Show graphic
plt.show()

0

我想展示另一种方法。如果你喜欢Matplotlib,可以选择@Burning Alcohol提供的解决方案。

import pandas as pd
counts = {
    "Elton John": 18,
    "The Beatles": 16,
    "Elvis Presley": 12,
    "The Jimi Hendrix Experience": 12,
    "The Four Tops": 10,
    "Muddy Waters": 8,
    "Sam Cooke": 8,
    "The Clash": 8,
    "U2": 8,
    "The Isley Brothers": 8
}

从字典创建一个DataFrame。

df = pd.DataFrame.from_dict([counts])

以下是一个带有图例的条形图,图例位于框外。
axes = df.plot.bar()
axes.legend(bbox_to_anchor=(1,1))

另一种方法是将标签放在x轴上。我们首先转置数据框。

tdf = df.T.reset_index()
tdf.columns = ['Artist', 'Counts']

最后是情节。

tdf.plot.bar(x='Artist', y='Counts')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接