gpt4 book ai didi

python - 如何制作凹凸图

转载 作者:行者123 更新时间:2023-12-05 01:29:01 25 4
gpt4 key购买 nike

我有一个排名数据表,我想将其可视化为凹凸图或斜率图,例如

我知道如何绘制一个,但如果说我从 pandas 中了解到一件事,那就是通常有一些融化、合并、发泡和摆弄的组合,可以在一个类轮中完成这项工作。又名优雅的 Pandas ,而不是杂乱无章的 Pandas 。

数据看起来有点像这样:(much more data here)

<表类="s-表"><头>ed_name来源<正文>2562edition_3gq2956edition_8warontherocks10168edition_12aeon.co1137edition_14hbr.org4573edition_13thesmartnik7143edition_16vijayboyapati.medium9674edition_15中等5555edition_9smh.au8831edition_11沙龙8215edition_14thegospelcoalition.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()

这给出了类似的东西:

enter image description here

至少可以说,还有很多不足之处。很多问题都可以通过使用标准的 matplotlib 东西来解决,但我很犹豫是否要这样做,因为它感觉不雅,而且我可能缺少一个内置的 bumpchart 方法。

This question问了一个类似的问题,但是the answer将其作为斜率图求解。它们看起来很棒,但这是另一种类型的图表。

有没有更优雅的方法来做到这一点?

最佳答案

我认为您没有遗漏一些内置方法。我不确定您的数据与凹凸图的匹配程度如何,因为版本之间的差异似乎非常大,而且多个来源似乎具有相同的排名,但我尝试找点乐子。

读取/排序数据

import pandas as pd

data_source = (
"https://gist.githubusercontent.com/"
"notionparallax/7ada7b733216001962dbaa789e246a67/raw/"
"6d306b5d928b04a5a2395469694acdd8af3cbafb/example.csv"
)

df = (
pd.read_csv(data_source, index_col=0)
.assign(ed_name=lambda x: x["ed_name"].str.extract(r"(\d+)").astype(int))
.value_counts(["ed_name", "source"])
.groupby("ed_name")
.rank("first", ascending=False)
.rename("rank")
.sort_index()
.reset_index()
.query("ed_name < 17")
)

在这里我选择按“第一”排名,因为这会给我们排他性的排名而不是重叠的排名。它使情节看起来稍微好一点,但可能不是你想要的。如果您想要重叠排名,请使用“min”而不是 first。

获取上一版的前n名(用于标注)

n_top_ranked = 10
top_sources = df[df["ed_name"] == df["ed_name"].max()].nsmallest(n_top_ranked, "rank")

简单的情节

import matplotlib.pyplot as plt
for i, j in df.groupby("source"):
plt.plot("ed_name", "rank", "o-", data=j, mfc="w")
plt.ylim(0.5, 0.5 + n_top_ranked)
plt.gca().invert_yaxis()

这里生成的图不是很好,但制作起来很简单。

enter image description here

让剧情好看一点

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FixedFormatter, FixedLocator

fig, ax = plt.subplots(figsize=(8, 5), subplot_kw=dict(ylim=(0.5, 0.5 + n_top_ranked)))

ax.xaxis.set_major_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(1))

yax2 = ax.secondary_yaxis("right")
yax2.yaxis.set_major_locator(FixedLocator(top_sources["rank"].to_list()))
yax2.yaxis.set_major_formatter(FixedFormatter(top_sources["source"].to_list()))

for i, j in df.groupby("source"):
ax.plot("ed_name", "rank", "o-", data=j, mfc="w")

ax.invert_yaxis()
ax.set(xlabel="Edition", ylabel="Rank", title="Popularity of publisher by edition")
ax.grid(axis="x")
plt.tight_layout()

这给你以下 enter image description here

这里仍有工作要做才能使它看起来非常漂亮(例如,颜色需要排序),但希望这个答案中的某些内容能让您更接近您的目标。

关于python - 如何制作凹凸图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68095438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com