如何在图表上按顺序列出x轴和y轴?

2024-10-04 09:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框,我想在图表上显示它们。当我启动代码时,xy轴是非顺序的。我怎样才能解决它?此外,我还给出了一个图片上的示例图。第一张是我的,第二张是我想要的

这是我的代码:


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()

这是我的图表:

current graph

这是我想要的图表:

desired graph


Tags: inimportfordatetimedatevalueas图表
2条回答

日期时间x轴

因此,这段代码似乎正在打开一个文本文件,向日期列表或值列表添加值,然后用这些列表创建一个数据框架。最后,它用线图绘制日期和值

几处更改将帮助您的图形看起来更好。其中很多都是非常基础的,我建议您阅读一些matplotlib教程。在我看来,真正的Python tutorial是一个很好的起点

固定y轴限制:

plt.set_ylim(0, 100)

使用来自mdates的x轴定位器来查找间距更好的x标签位置,这取决于您的时间范围,但我制作了一些数据并使用了日定位器

import matplotlib.dates as mdates
plt.xaxis.set_major_locator(mdates.DayLocator())

使用散点图添加链接图上的数据点

plt.scatter(x, y ... )

添加网格

plt.grid(axis='both', color='gray', alpha=0.5)

旋转x记号标签

plt.tick_params(axis='x', rotation=45)

我模拟了一些数据,并将其绘制成您链接的绘图,这可能对您的工作有所帮助

enter image description here

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.dates as mdates

fig, ax = plt.subplots(figsize=(15,5))

x = pd.date_range(start='june 26th 2021', end='july 25th 2021')
rng = np.random.default_rng()
y = rng.integers(low=15, high=25, size=len(x))

ax.plot(x, y, color='gray', linewidth=2)
ax.scatter(x, y, color='gray')

ax.set_ylim(0,100)
ax.grid(axis='both', color='gray', alpha=0.5)
ax.set_yticks(np.arange(0,101, 10))
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.tick_params(axis='x', rotation=45)
ax.set_xlim(min(x), max(x))

主要问题是fg['date']fg['fg_value']目前是字符串(这就是line.split(',')产生的)。需要将它们转换为datetimefloat类型,以便matplotlib对它们进行正确排序

例如,字符串日期的排序方式为01-06->01-07而适当的datetime日期被排序为01-06->02-06

  1. 转换日期^{}和值^{}
  2. 使用^{}将x记号设置为日期样式
  3. 如果希望天有一个刻度标签,请使用^{}调整间隔
  4. 如果希望日期显示为25 Jul, 2021而不是25-07-2021,请使用^{}

figure output with formatted dates

#1 - convert to datetime and float
fg['date'] = pd.to_datetime(fg['date'], dayfirst=True)
fg['fg_value'] = fg['fg_value'].astype(float)
plt.plot(fg['date'], fg['fg_value'], marker='.')

#2 - style tick labels as dates
plt.gcf().autofmt_xdate()

#3 - change tick interval to every day
import matplotlib.dates as mdates
loc = mdates.DayLocator(interval=1)
plt.gca().xaxis.set_major_locator(loc)

#4 - change tick format from 01-07-2021 to 01 Jul, 2021
fmt = mdates.DateFormatter('%d %b, %Y')
plt.gca().xaxis.set_major_formatter(fmt)

相关问题 更多 >