在matplotlib中绘图并修复x轴。

huangapple go评论71阅读模式
英文:

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

一切正常,我得到了以下图表:

在matplotlib中绘图并修复x轴。

问题是我看不到横轴上的日期值。有没有办法格式化轴?

我尝试了以下方法:

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轴上绘制时间序列时出现错误结果。

在matplotlib中绘图并修复x轴。

我如何格式化原始图像的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&#39;Plot_Example.csv&#39;,sep=&#39;;&#39;)
df = df.set_index(&quot;Date&quot;)

fig, ax = plt.subplots() 
fig.set_size_inches(18.5, 18.5)
ax.plot(df[&quot;Yt&quot;], label=&quot;Yt&quot;,color=&#39;blue&#39;) 
ax.plot(df[&quot;X1t&quot;], label=&quot;X1t&quot;,color=&#39;red&#39;) 
ax.plot(df[&quot;X2t&quot;],
label=&quot;X2t&quot;,color=&#39;yellow&#39;) 
ax.legend() fig.savefig(&#39;test3png.png&#39;,dpi=100)

For some more information:

df.info()

&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt; 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:

在matplotlib中绘图并修复x轴。

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&#39;Plot_Example.csv&#39;,sep=&#39;;&#39;)
df[&quot;Date&quot;] = pd.to_datetime(df[&quot;Date&quot;])
df = df.set_index(&quot;Date&quot;)

fig, ax = plt.subplots() 
fig.set_size_inches(18.5, 18.5)
ax.plot(df[&quot;Yt&quot;], label=&quot;Yt&quot;,color=&#39;blue&#39;) 
ax.plot(df[&quot;X1t&quot;],
label=&quot;X1t&quot;,color=&#39;red&#39;) 
ax.plot(df[&quot;X2t&quot;], label=&quot;X2t&quot;, color=&#39;yellow&#39;) 
years = mdates.YearLocator() 
yearsFmt = mdates.DateFormatter(&#39;\n%Y&#39;) ?
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt) 
ax.legend()
fig.savefig(&#39;test3png.png&#39;, 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.

在matplotlib中绘图并修复x轴。

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=&#39;right&#39;
)

huangapple
  • 本文由 发表于 2023年7月13日 20:05:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定