gpt4 book ai didi

python - 防止按组将 xaxis 中的字符串转换为 int

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

我尝试使用Python中的matplotlib.pyplot库制作分组图。我想要将日期签名作为字符串,呈现在x轴上。尽管我将其值(“day_date”列)定义为字符串,但结果图仍将值显示为 int-s。

如何将 x 轴值显示为字符串?(请注意,我不想将它们转换为任何专用的日期格式)。

# Define data frame 
day_date = ['20151103', '20151103', '20151103', '20151103', '20151103', '20151103', '20151104', '20151104', '20151104', '20151104', '20151104', '20151104', '20151105', '20151105', '20151105', '20151105', '20151105', '20151105', '20151106', '20151106', '20151106', '20151106', '20151106', '20151106', '20151107', '20151107', '20151107', '20151107', '20151107', '20151107', '20151108', '20151108', '20151108', '20151108', '20151108', '20151108']
country_code = ['BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US', 'BY', 'DE', 'ID', 'PL', 'RU', 'US']
val = [35989, 64488, 72879, 73586, 192538, 54474, 137322, 227274, 307893, 249741, 683455, 288863, 179319, 287662, 455944, 321588, 854791, 342946, 207263, 326290, 558362, 361792, 981566, 390313, 224863, 369141, 637215, 415884, 1031772, 429145, 272623, 419612, 702541, 497348, 1160243, 462813]

df_tmp = pd.DataFrame([day_date, country_code, val]).T
df_tmp.columns = ['day_date','country_code','val']
df_tmp.head()

# Plot
fig, ax = plt.subplots()
for name, group in df_tmp.groupby('country_code'):
ax.plot(group.day_date, group.val, label=name)

ax.legend()
plt.show()

enter image description here

最佳答案

目前还不清楚您想做什么。您必须向 plt 提供一些有关放置点的位置的信息,即 x 值。字符串不能满足此要求。每天可以有多个条目吗?如果没有,你可以这样做:

dates = sorted(list(set(day_date)))
# Plot
fig, ax = plt.subplots()
for name, group in df_tmp.groupby('country_code'):
xvals = [dates.index(d) for d in group.day_date]
ax.plot(xvals, group.val, label=name)

plt.xticks(range(len(dates)),dates,rotation = 45)

关于python - 防止按组将 xaxis 中的字符串转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33875476/

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