【发布时间】:2021-06-23 07:31:14
【问题描述】:
我有一张排名数据表,我想将其可视化为凹凸图或斜率图,例如
我知道如何绘制一个,但如果我学到了关于 pandas 的一件事,那就是通常有一些融化、合并、起泡和摆弄的组合可以在一个班轮中完成这项工作。又名优雅的熊猫,而不是打乱的熊猫。
数据看起来有点像这样:(much more data here)
| ed_name | source | |
|---|---|---|
| 2562 | edition_3 | gq |
| 2956 | edition_8 | warontherocks |
| 10168 | edition_12 | aeon.co |
| 1137 | edition_14 | hbr.org |
| 4573 | edition_13 | thesmartnik |
| 7143 | edition_16 | vijayboyapati.medium |
| 9674 | edition_15 | medium |
| 5555 | edition_9 | smh.au |
| 8831 | edition_11 | salon |
| 8215 | edition_14 | thegospelcoalition.org |
以此类推,其中每一行是一篇文章,来源是该文章的来源。目标是找出每个版本中哪些来源贡献的文章最多。
这是我笨拙地将其转换为不良凹凸图的尝试:
all_sources = set(sources)
source_rankings = {}
for s in all_sources:
source_rankings[s]={}
for ed in printed.groupby("ed_name"):
df = ed[1]
vc = df.source.value_counts()
for i, x in enumerate(vc.index):
source_rankings[x][ed[0]] = i+1
ranks = pd.DataFrame(source_rankings)
cols_to_drop = []
for name, values in ranks.iteritems():
interesting = any([x>30 for x in list(values) if not math.isnan(x)])
# print(name, interesting)
if interesting:
cols_to_drop.append(name)
only_interesting = ranks.drop(labels=cols_to_drop, axis='columns')
only_interesting.sort_index(
axis=0, inplace=True,
key=lambda col: [int(x.split("_")[1]) for x in col],
ascending=False
)
linestyles = ['-', '--', '-.', ':']
plt.plot(only_interesting, alpha=0.8, linewidth=1)
plt.ylim(25, 0)
plt.gca().invert_xaxis()
plt.xticks(rotation=70)
plt.title("Popularity of publisher by edition")
editions_that_rank_threshold = 10
for name, values in only_interesting.iteritems():
if len(values[values.isna() == False]) > editions_that_rank_threshold:
for i, x in values.iteritems():
if not math.isnan(x):
# print(name, i, x)
plt.annotate(xy=(i,x), text=name)
plt.plot(values, linewidth=5, linestyle=sample(linestyles,1)[0])
break
plt.xlabel("Edition")
plt.ylabel("Cardinal Rank (1 at the top)")
plt.close()
这给出了类似的东西:
至少可以说,还有很多不足之处。很多问题都可以通过使用标准的 matplotlib 东西来解决,但我很犹豫,因为它感觉不优雅,而且我可能缺少一个内置的 bumpchart 方法。
This question 提出了类似的问题,但the answer 将其作为斜率图解决。它们看起来很棒,但这是一种不同类型的图表。
有没有更优雅的方法来做到这一点?
【问题讨论】:
-
mplsoccer 库中有一个函数可以绘制bump chart。我希望这会有所帮助。
标签: python pandas matplotlib