英文:
Plotting in matplotlib and fixing the x axis
问题
我正在尝试使用matplotlib在Python中创建一个图表。首先,我编写了以下代码:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r'Plot_Example.csv', sep=';')
df = df.set_index("Date")
fig, ax = plt.subplots()
fig.set_size_inches(18.5, 18.5)
ax.plot(df["Yt"], label="Yt", color='blue')
ax.plot(df["X1t"], label="X1t", color='red')
ax.plot(df["X2t"], label="X2t", color='yellow')
ax.legend()
fig.savefig('test3png.png', dpi=100)
关于更多信息:
df.info()
<class 'pandas.core.frame.DataFrame'> Index: 96 entries, 1/1/1949 to
1/12/1956 Data columns (total 3 columns): # Column Non-Null Count
Dtype
--- ------ -------------- ----- 0 Yt 96 non-null int64 1 X1t 96 non-null int64 2 X2t 96 non-null int64
dtypes: int64(3) memory usage: 2.6+ KB
一切正常,我得到了以下图表:
问题是我看不到横轴上的日期值。有没有办法格式化轴?
我尝试了以下方法:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import YearLocator, DateFormatter
df = pd.read_csv(r'Plot_Example.csv', sep=';')
df["Date"] = pd.to_datetime(df["Date"])
df = df.set_index("Date")
fig, ax = plt.subplots()
fig.set_size_inches(18.5, 18.5)
ax.plot(df["Yt"], label="Yt", color='blue')
ax.plot(df["X1t"], label="X1t", color='red')
ax.plot(df["X2t"], label="X2t", color='yellow')
years = mdates.YearLocator()
yearsFmt = mdates.DateFormatter('\n%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.legend()
fig.savefig('test3png.png', dpi=100)
我得到了漂亮的x轴格式化,但在y轴上绘制时间序列时出现错误结果。
我如何格式化原始图像的x轴或修复第二个图像中的时间序列绘制?
英文:
I am trying to create a plot in Python using matplotlib. I write first the following code:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r'Plot_Example.csv',sep=';')
df = df.set_index("Date")
fig, ax = plt.subplots()
fig.set_size_inches(18.5, 18.5)
ax.plot(df["Yt"], label="Yt",color='blue')
ax.plot(df["X1t"], label="X1t",color='red')
ax.plot(df["X2t"],
label="X2t",color='yellow')
ax.legend() fig.savefig('test3png.png',dpi=100)
For some more information:
df.info()
<class 'pandas.core.frame.DataFrame'> Index: 96 entries, 1/1/1949 to
1/12/1956 Data columns (total 3 columns): # Column Non-Null Count
Dtype
--- ------ -------------- ----- 0 Yt 96 non-null int64 1 X1t 96 non-null int64 2 X2t 96 non-null int64
dtypes: int64(3) memory usage: 2.6+ KB
All good, I get the following graph:
The problem is that I cannot see the date values in the horizontal axis. Is there a way to format the axis?
I have tried the following:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import YearLocator, DateFormatter
df = pd.read_csv(r'Plot_Example.csv',sep=';')
df["Date"] = pd.to_datetime(df["Date"])
df = df.set_index("Date")
fig, ax = plt.subplots()
fig.set_size_inches(18.5, 18.5)
ax.plot(df["Yt"], label="Yt",color='blue')
ax.plot(df["X1t"],
label="X1t",color='red')
ax.plot(df["X2t"], label="X2t", color='yellow')
years = mdates.YearLocator()
yearsFmt = mdates.DateFormatter('\n%Y') ?
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.legend()
fig.savefig('test3png.png', dpi=100)
I get nice formatting of the x-axis, but I get erroneous results in the plotting of the time series on the y-axis.
How can I format the x-axis from the original image or fix the time-series plotting in the second image?
答案1
得分: 1
你可以仅保留 x 轴上每第 n 个日期(在下面的代码中,我选择了 n=10)。此外,你可以旋转标签以避免重叠:
tick_spacing = 10
plt.xticks(
ax.get_xticks()[::tick_spacing],
ax.get_xticklabels()[::tick_spacing],
rotation=45,
ha='right'
)
英文:
You can keep only every n-th date on your x-axis (in the code below I chose n=10). Additionally, you can rotate the labels to avoid overlap:
tick_spacing = 10
plt.xticks(
ax.get_xticks()[::tick_spacing],
ax.get_xticklabels()[::tick_spacing],
rotation=45,
ha='right'
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论