在matplotlib中绘图并修复x轴。

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

Plotting in matplotlib and fixing the x axis

问题

我正在尝试使用matplotlib在Python中创建一个图表。首先,我编写了以下代码:

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. df = pd.read_csv(r'Plot_Example.csv', sep=';')
  4. df = df.set_index("Date")
  5. fig, ax = plt.subplots()
  6. fig.set_size_inches(18.5, 18.5)
  7. ax.plot(df["Yt"], label="Yt", color='blue')
  8. ax.plot(df["X1t"], label="X1t", color='red')
  9. ax.plot(df["X2t"], label="X2t", color='yellow')
  10. ax.legend()
  11. fig.savefig('test3png.png', dpi=100)

关于更多信息:

  1. df.info()
  2. <class 'pandas.core.frame.DataFrame'> Index: 96 entries, 1/1/1949 to
  3. 1/12/1956 Data columns (total 3 columns): # Column Non-Null Count
  4. Dtype
  5. --- ------ -------------- ----- 0 Yt 96 non-null int64 1 X1t 96 non-null int64 2 X2t 96 non-null int64
  6. dtypes: int64(3) memory usage: 2.6+ KB

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

在matplotlib中绘图并修复x轴。

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

我尝试了以下方法:

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. from matplotlib.dates import YearLocator, DateFormatter
  4. df = pd.read_csv(r'Plot_Example.csv', sep=';')
  5. df["Date"] = pd.to_datetime(df["Date"])
  6. df = df.set_index("Date")
  7. fig, ax = plt.subplots()
  8. fig.set_size_inches(18.5, 18.5)
  9. ax.plot(df["Yt"], label="Yt", color='blue')
  10. ax.plot(df["X1t"], label="X1t", color='red')
  11. ax.plot(df["X2t"], label="X2t", color='yellow')
  12. years = mdates.YearLocator()
  13. yearsFmt = mdates.DateFormatter('\n%Y')
  14. ax.xaxis.set_major_locator(years)
  15. ax.xaxis.set_major_formatter(yearsFmt)
  16. ax.legend()
  17. 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:

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. df = pd.read_csv(r&#39;Plot_Example.csv&#39;,sep=&#39;;&#39;)
  4. df = df.set_index(&quot;Date&quot;)
  5. fig, ax = plt.subplots()
  6. fig.set_size_inches(18.5, 18.5)
  7. ax.plot(df[&quot;Yt&quot;], label=&quot;Yt&quot;,color=&#39;blue&#39;)
  8. ax.plot(df[&quot;X1t&quot;], label=&quot;X1t&quot;,color=&#39;red&#39;)
  9. ax.plot(df[&quot;X2t&quot;],
  10. label=&quot;X2t&quot;,color=&#39;yellow&#39;)
  11. ax.legend() fig.savefig(&#39;test3png.png&#39;,dpi=100)

For some more information:

  1. df.info()
  2. &lt;class &#39;pandas.core.frame.DataFrame&#39;&gt; Index: 96 entries, 1/1/1949 to
  3. 1/12/1956 Data columns (total 3 columns): # Column Non-Null Count
  4. Dtype
  5. --- ------ -------------- ----- 0 Yt 96 non-null int64 1 X1t 96 non-null int64 2 X2t 96 non-null int64
  6. 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:

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. from matplotlib.dates import YearLocator, DateFormatter
  4. df = pd.read_csv(r&#39;Plot_Example.csv&#39;,sep=&#39;;&#39;)
  5. df[&quot;Date&quot;] = pd.to_datetime(df[&quot;Date&quot;])
  6. df = df.set_index(&quot;Date&quot;)
  7. fig, ax = plt.subplots()
  8. fig.set_size_inches(18.5, 18.5)
  9. ax.plot(df[&quot;Yt&quot;], label=&quot;Yt&quot;,color=&#39;blue&#39;)
  10. ax.plot(df[&quot;X1t&quot;],
  11. label=&quot;X1t&quot;,color=&#39;red&#39;)
  12. ax.plot(df[&quot;X2t&quot;], label=&quot;X2t&quot;, color=&#39;yellow&#39;)
  13. years = mdates.YearLocator()
  14. yearsFmt = mdates.DateFormatter(&#39;\n%Y&#39;) ?
  15. ax.xaxis.set_major_locator(years)
  16. ax.xaxis.set_major_formatter(yearsFmt)
  17. ax.legend()
  18. 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)。此外,你可以旋转标签以避免重叠:

  1. tick_spacing = 10
  2. plt.xticks(
  3. ax.get_xticks()[::tick_spacing],
  4. ax.get_xticklabels()[::tick_spacing],
  5. rotation=45,
  6. ha='right'
  7. )
英文:

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:

  1. tick_spacing = 10
  2. plt.xticks(
  3. ax.get_xticks()[::tick_spacing],
  4. ax.get_xticklabels()[::tick_spacing],
  5. rotation=45,
  6. ha=&#39;right&#39;
  7. )

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:

确定