嗨,专家们,我想做一个漂亮的条形图使用附加的数据(data.txt)。在x轴上我想绘制年份,如2007,2008等从第一列数据和y轴上对应的第二列data.Most重要的是,我想只提到一次年份,如2007年2008沿着x轴只有一次,因为在x轴标签上看不到由于巨大的数据。
示例数据如下所示
2008-05-23 5.1
2008-05-21 6.5
2008-05-26 2.3
2008-06-10 3.7
2008-05-12 6.2
2008-07-06 5.7
2008-07-31 3.0我在下面尝试过:脚本
import numpy as np
import matplotlib.pyplot as plt
x=np.loadtxt('data.txt')
plt.plot(x)
plt.show()发布于 2021-07-08 00:09:18
matplotlib文档是一个很好的起点:https://matplotlib.org/stable/gallery/index.html
这应该是可行的:
import numpy as np
import matplotlib.pyplot as plt
xlabels = ["2007-11-05","2007-11-07",
"2007-11-07","2008-01-17",
"2008-02-17","2008-02-18",
"2008-04-12"]
y = [8.5,8.8,8.3, 8.3, 8.2,4.4,6.5]
x = np.arange(len(xlabels))
fig, ax = plt.subplots()
ax.bar(x, y)
plt.xticks(ticks = x, labels = xlabels, rotation = 90)
plt.show()发布于 2021-07-08 01:50:03
将列x的dtype更改为datetime,然后使用dt访问器获取year,然后按year对数据帧进行分组,并使用sum聚合列y。现在使用plot方法创建条形图
df.groupby(pd.to_datetime(df['x']).dt.year)['y'].sum().plot(kind='bar');结果条形图:

发布于 2021-07-08 23:02:46
import pandas as pd
file = pd.read_csv("data.txt", sep='\t')
file['x'] = pd.to_datetime(file['x'], format='%Y/%m/%d')
fig, bx = plt.subplots()
bx.bar(file['x'], file['y'])
bx.set_xlabel('Year')
bx.set_ylabel('Amplitude')或者,您也可以采取一种变通方法(如果条形图显示的值不正确,请替换
bx.bar(file['x'], file['y'])使用
bx.vlines(file['x'], 0, file['y'])当您的数据变大时,x轴上的年份标签将自动适应自身。
https://stackoverflow.com/questions/68289208
复制相似问题