【问题标题】:Matplotlib xticks hides graph cursor informationMatplotlib xticks 隐藏图形光标信息
【发布时间】:2020-09-06 19:34:16
【问题描述】:

我有一个带有 aprox 的 csv 文件。 3000行,格式如下:

Timestamp,PV Generation (W)
2019-01-01 00:00:00,616.54
2019-01-01 00:15:00,617.75
2019-01-01 00:30:00,752.56

我正在使用 pandas 来阅读它:

columnnames = ['Timestamp','PV Generation (W)'] 
df = pandas.read_csv(filename, sep=',', engine='python', names=columnnames,index_col=None)  
timestamp = df['Timestamp']
pvgeneration = df['PV Generation (W)']
pvgenerationlist=pvgeneration.tolist() #create a list with pvgeneration column 
timestamplist=timestamp.tolist() #create a list with timestamp column

因为每列的第一行是标题,所以我删除了每个列表的第一个元素:

timestamplist.pop(0)  
pvgenerationlist.pop(0) 

pvgeneration 值是一个字符串,所以我将它们更改为浮点数:

pvgenfloat = []
for item in pvgenerationlist:
    pvgenfloat.append(float(item))

我现在有两个列表,我希望使用 matplotlib 进行绘图。我希望 Y 轴具有浮点 PV 生成值,而 X 轴具有一些时间戳字符串值。

plt.plot(timestamplist,pvgenfloat)

造成混乱,因为它在 X 轴上绘制了 3000 个时间戳。

通过使用鼠标悬停在图表上,我可以读取图表下方的值: x=2019-01-01 00:00:00 y=616.54

所以我尝试使用 plt.xticks 仅绘制我的时间戳列表的第一个和最后一个字符串元素:

xlisttoplot=[''] * len(timestamplist)  #i create a new list to plot with same length but blank elements
xlisttoplot[0]=timestamplist[0] #i keep the first element of the timestamp list which is 2019-01-01 00:00:00 
xlisttoplot[-1]=timestamplist[-1] #and i also keep the last one
plt.xticks(timestamplist,xlisttoplot,rotation=45,size = 8)

上面的工作,它只绘制 X 中的第一个和最后一个值,但现在我不能使用鼠标悬停在这些值上。悬停显示:x= y=616.54

我需要通过悬停来读取数据。 关于如何解决这个问题的任何线索,或者以不同的方式做同样的事情? 谢谢

【问题讨论】:

  • 如果您的问题得到解决,请通过检查为已接受和/或按向上箭头表示感谢。如果出现更好的选择,您可以随时更改您的选择。检查位于答案左上角的向上/向下箭头下方。如果它没有回答问题,请发表评论。 stackoverflow.com/help/someone-answers

标签: python-3.x pandas matplotlib


【解决方案1】:

您可以直接从 pandas 数据框中进行绘图。

from matplotlib import pyplot as plt

df = pandas.read_csv(filename, sep=',', engine='python', index_col=None)

# pandas reads the first line as column names by default
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
df['PV Generation (W)'] = df['PV Generation (W)'].astype(float)

# set `Timestamp` as index so it will become the x-axis
df.set_index('Timestamp', inplace=True)

df.plot()
plt.show()

输出

Pandas 将减少传递给 matplotlib 的 x-labels 的数量。 (老实说,我不确定它是由 pandas 还是由 matplotlib 日期解析器处理的)。无论如何,结果在 x 轴上的日期会更少,以使它们可读。

否则,您可以像this question一样控制xticks

【讨论】:

  • 这段代码几乎可以工作。它没有在 X 轴上绘制时间戳,而是在 Y 轴上绘制年度划分(1990,2000,2010,2020),然后将时间戳绘制为高度的直线(如果日期是 2019 年)。我不是熟悉熊猫,但我认为 pd.to_datetime 只读取年份。有关如何解决此问题并在 X 轴上绘制日期的任何线索或链接?谢谢先生。
  • @S.Filip 这是因为df 有一个默认的 RangeIndex,现在就试试吧
  • 非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多