我有一个数据框,我想在图表上显示它们。当我启动代码时,x
和y
轴是非顺序的。我怎样才能解决它?此外,我还给出了一个图片上的示例图。第一张是我的,第二张是我想要的
这是我的代码:
from datetime import timedelta, date
import datetime as dt #date analyse
import matplotlib.pyplot as plt
import pandas as pd #read file
def daterange(date1, date2):
for n in range(int ((date2 - date1).days)+1):
yield date1 + timedelta(n)
tarih="01-01-2021"
tarih2="20-06-2021"
start=dt.datetime.strptime(tarih, '%d-%m-%Y')
end=dt.datetime.strptime(tarih2, '%d-%m-%Y')
fg=pd.DataFrame()
liste=[]
tarih=[]
for dt in daterange(start, end):
dates=dt.strftime("%d-%m-%Y")
with open("fng_value.txt", "r") as filestream:
for line in filestream:
date = line.split(",")[0]
if dates == date:
fng_value=line.split(",")[1]
liste.append(fng_value)
tarih.append(dates)
fg['date']=tarih
fg['fg_value']=liste
print(fg.head())
plt.subplots(figsize=(20, 10))
plt.plot(fg.date,fg.fg_value)
plt.title('Fear&Greed Index')
plt.ylabel('Fear&Greed Data')
plt.xlabel('Date')
plt.show()
这是我的图表:
这是我想要的图表:
日期时间x轴
因此,这段代码似乎正在打开一个文本文件,向日期列表或值列表添加值,然后用这些列表创建一个数据框架。最后,它用线图绘制日期和值
几处更改将帮助您的图形看起来更好。其中很多都是非常基础的,我建议您阅读一些matplotlib教程。在我看来,真正的Python tutorial是一个很好的起点
固定y轴限制:
使用来自mdates的x轴定位器来查找间距更好的x标签位置,这取决于您的时间范围,但我制作了一些数据并使用了日定位器
使用散点图添加链接图上的数据点
添加网格
旋转x记号标签
我模拟了一些数据,并将其绘制成您链接的绘图,这可能对您的工作有所帮助
主要问题是
fg['date']
和fg['fg_value']
目前是字符串(这就是line.split(',')
产生的)。需要将它们转换为datetime
和float
类型,以便matplotlib对它们进行正确排序例如,字符串日期的排序方式为
01-06
->01-07
而适当的datetime
日期被排序为01-06
->02-06
25 Jul, 2021
而不是25-07-2021
,请使用^{相关问题 更多 >
编程相关推荐