首页 > 解决方案 > 如何将 Pyplot 输出图上的 X 轴调整到正确的位置?

问题描述

我正在使用 Pandas 和 Pyplot 处理来自 CSV 数据的地面阵风数据。我从文件中提取的数据看起来不错并且绘制正确,但是由于我不知道的原因,这张图似乎奇怪地漂浮在轴上方。这是一个屏幕截图来说明我的意思:

在此处输入图像描述

我想让那个图沿着 x 轴很好地对齐。考虑到我的数据是从 5 月开始的,我对左边的空白并不担心,我稍后会弄清楚。所以我的问题是如何让图表按照我想要的方式对齐?我试过移动子图轴,但这只是扩大了窗口中的图。此外,如果您愿意提供其他格式建议以使其尽可能干净和专业,我将不胜感激!

这是我用来生成它的代码:

#Import packages and assign to variables
import pandas as pd
import csv
from matplotlib import pyplot as plt
import os

#Change working directory to where file is located
cwd = os.getcwd()
os.chdir("C:/Users/zrr81/Downloads/Climate Dev/Python/Synoptic Client Data")

#Read in file
data = pd.read_csv('KCDC.2019-11-01.csv')

#Build wind gust and datetime DataFrame
gust = pd.DataFrame(data, columns = ['Date_Time', 'wind_gust'])
#Drop all rows that don't contain a gust (inplace)
gust.dropna(how = 'any', inplace = True)
#Drop unit/ header row
gust = gust.drop(gust.index[0])
#Convert data types from objects to datetime and float
gust['Date_Time'] = pd.to_datetime(gust['Date_Time'])
gust['wind_gust'] = gust['wind_gust'].astype(str).astype(float)
print(gust)      #Outputs datetime and float
print(gust.dtypes)

#Plot max wind speeds, gusts, and times
ax = plt.gca()
gust.plot(kind = 'line' , x = 'Date_Time', y = 'wind_gust', color = 'red')
#plt.plot(zw.year, zw.population)
plt.legend(['Wind gusts'])
plt.xlabel("Date Time")
plt.ylabel("Wind Gust (m/s)")
plt.title("May-Nov Maximum Wind Gusts at KCDC")
plt.show()

**编辑:澄清一下,我相信 y 轴向上移动了 7.5 并且需要向下移动到原点(在标题中也澄清了这一点)。我正在寻找有关如何解决此问题的建议

标签: pythonpandasmatplotlibformatting

解决方案


推荐阅读