python - 无法在 pyplot 图表中按月对 x 轴进行分组(Python)
问题描述
我正在使用 python 开始我的第一个“项目”,我需要一些帮助。
我正在使用 pyplot 创建一个图表,显示自创建帐户以来我在 Linkedin 的连接数如何增长。
我在尝试按月和年对 X 轴进行分组时遇到问题。我发现将它们分组的方式并不好,因为它跳过了我没有任何新联系的那几个月。
我想知道是否有人知道我该如何解决这个问题。
import pandas as pd
import datetime
import matplotlib.pyplot as plt
from matplotlib import rcParams
df = pd.read_csv("/Users/ignaciolorenzoqueralt/Desktop/linkedin.pythonproject/connections_clean.csv")
df.head(2)
def fun(date):
return datetime.datetime.strptime(date,"%d %b %Y").strftime("%Y-%m")
df["Connected On"] = df["Connected On"].apply(fun)
df = df.sort_values(by="Connected On")
df.reset_index(inplace=True)
df.reset_index(inplace=True)
df.drop(columns="index",inplace=True)
df.rename(columns={"level_0":"number"},inplace=True)
print(df)
x = df["Connected On"]
y = df["number"]
rcParams["figure.figsize"] = 15,8
plt.plot(x, y, label="Ignacio's nº of Connections")
plt.xlabel("Date")
plt.ylabel("Number of connections")
plt.xticks(rotation=45)
plt.legend()
#plt.grid()
plt.show()
Here is what I have coded:
附加到此链接(https://docs.google.com/spreadsheets/d/1yIGQGoCcmq0JOD2Im0B8CQ0oT2fqFh5cKxKO5i8_uAU/edit?usp=sharing)您会发现没有此项目所基于的 csv 私人信息的副本。
非常感谢您。
解决方案
您的问题基本上有两个部分:
- 对数据进行分组(否则当每月有多个条目时,绘图会导致奇怪的结果)
- 绘制数据并解释“缺失值”,即没有条目的月份
第一部分可以解决
#get unique months --> no duplicate x values
x = df["Connected On"].unique()
#group by months, then take max number for each month
y = df.groupby("Connected On").max()["number"]
第二部分与 matplotlib 如何处理日期有关。我认为在您的情况下,日期被解释为strings
,因此每个 x,y 对的绘制在 x 轴上没有任何线性。为了实现时间线性和连续性,您需要为 matplotlib 提供完整的日期时间对象,这可以通过
x = pd.to_datetime(df["Connected On"].unique())
结果:
推荐阅读
- html - 我可以使用 span 标签制作 HTML 电子邮件模板吗?
- java - Kotlin String toDouble() 函数不解析某些值?
- r - 在R中的一段时间内从数据帧中创建特定单词的频率图
- mysql - 从包含多行数据的表中更新表
- regex - 忽略正则表达式中一组数字之间的空格?
- android - Android RecyclerView submitList 未更新 LiveData 观察者中的数据
- java - 重载解析,调用哪个方法
- python - tag_name("a") 中的 "href" 抛出异常
- android - Disabled Rollout Button play console(无灰色勾号):Flutter update app App Bundle Format
- php - 如何将验证 laravel 控制器传递给甜蜜警报 swal