【问题标题】:Python - Pyplot x-axis not showing on graphPython - Pyplot x 轴未显示在图表上
【发布时间】:2018-08-19 14:54:27
【问题描述】:

pyplot 没有在图表上显示 x 轴:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('sitka_weather_2014.csv')    

df['AKST'] = pd.to_datetime(df.AKST)
df['Dates'] = df['AKST'].dt.strftime('%b %d, %Y')
df.set_index("Dates", inplace= True)

# Plot Data
fig = plt.figure(dpi=256, figsize=(14, 7))
plt.title("Daily high and low temperature - 2014")

df['Max TemperatureF'].plot(linewidth=1, c='blue', label="Max Temperature °F")
df['Min TemperatureF'].plot(linewidth=1, c='red', label="Min Temperature °F")

plt.grid(True)
plt.rc('grid', linestyle=":", linewidth=1, color='gray')

plt.legend(loc='upper left')

plt.xlabel('', fontsize=10)
plt.ylabel("Temperature (°F)", fontsize=10)
plt.tick_params(axis='both', which='major', labelsize=10)
fig.autofmt_xdate(rotation=45)

plt.show()

x 轴应该是包含日期的 Pandas Dataframe (df) 的索引。

【问题讨论】:

  • 请注意,您应该始终提供minimal reproducible example,以便其他人可以运行代码。否则人们怎么能知道在哪一点失败?
  • 无法模拟您的问题。当我使用自己的样本数据时,它看起来还不错。你如何运行python?通过笔记本?
  • @anonyXmous 是的,我通过 Junyper 笔记本运行 python,但使用 IDE 得到相同的结果。
  • 你能告诉我们你是如何定义数据框(df)的吗?如果可能,还包括数据。
  • @anonyXmous 我已经包含了整个代码,可以在这里获取 csv:github.com/crystalDf/…

标签: python matplotlib graph


【解决方案1】:

您将xlabel 值设置为null

plt.xlabel('', fontsize=10)

【讨论】:

  • 这可能并不能完全解决问题,因为还应该有刻度标签。请考虑更新答案。
【解决方案2】:

您的代码实际上很好。我尝试使用必要的sitka_weather_2014.csv 文件运行它,它可以工作。

问题是你看不到x轴,因为图的尺寸太大,因此x轴的描述消失了。尝试缩放你的身材,例如通过使dpi 更小:

fig = plt.figure(dpi=100, figsize=(14, 7)) #dpi=100 instead of dpi=256

或者将labelsize 缩小:

plt.tick_params(axis='both', which='major', labelsize=5) #labelsize=5 instead of labelsize=10

最适合你的。但是代码很好,并且显示了x轴的描述。

【讨论】:

  • @daquezada 我看到您对您在 StackOverflow 上发布的代码进行了一些编辑。您是否还运行了当前显示的代码(也许可以复制并粘贴它以确保)?因为当前的对我有用...
  • @V.L.在问题下方的 cmets 中,两个人已经说过代码确实会生成一个带有 标签的图。我怀疑回答是否有意义,再次说代码很好。只要提问者不能重现他的问题,这个问题根本就没有答案。
  • @V.L.如果代码适用于除我之外的所有人,我相信是开始假设问题可能出在我的 IDE 的正确时机。你怎么看?
猜你喜欢
  • 1970-01-01
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 2013-03-08
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多