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

How can I list sequentially the x and y axis on chart?

我有一个数据框,我想在图表上显示它们。当我开始我的代码时,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()

这是我的图表:

这是我想要的图表:

带日期时间 x 轴的线图

所以看起来这段代码正在打开一个文本文件,将值添加到日期列表或值列表,然后用这些列表制作一个 pandas 数据框。最后,它用线图绘制日期与值。

一些更改应该可以帮助您的图形看起来更好。其中很多都是非常基础的,我建议您查看一些 matplotlib 教程。在我看来,Real 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)

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

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