即使plt.subplots(sharex = True)在两个x轴上显示的值

时间:2018-11-07 01:13:47

标签: python pandas dataframe matplotlib

我正在处理有关用水量的小数据集。我有两个子图,我告诉他们共享x轴,但是,这些图并不代表这个事实。不使用此数据集时,可以使用plt.subplots(sharex = True)进行绘图,这使我想知道这是否是熊猫库和matplotlib库之间的问题。我的代码很简单,如下所示:

import pandas as pd
import matplotlib.pyplot as plt
# Source = https://data.cityofnewyork.us/Environment/Water-Consumption-In-The-New-York-City/ia2d-e54m

data_loc = 'D:\CSVs\Water_Consumption_In_The_New_York_City.csv'
df = pd.read_csv(data_loc, parse_dates=True)
#editing the population data to be per million
df['New York City Population'] = df['New York City Population']/1000000

fig, (ax1,ax2) = plt.subplots(2, figsize=(8,5), sharex = True)
ax1 = plt.subplot(211)
ax1.plot(df['Year'], df['NYC Consumption(Million gallons per day)'])
ax1.legend(['Water Consumption (Million Gallons per Day)'])

ax2 = plt.subplot(212)
ax2.plot(df['Year'], df['New York City Population'], color='red')
ax2.legend(['Population (In Millions)'])
plt.xlabel('Year')

plt.suptitle('NYC Water Consumption Data', size = 15)
plt.show()

此代码生成这些图形,它们不共享一个x轴:

enter image description here

提前谢谢

1 个答案:

答案 0 :(得分:1)

fig, (ax1,ax2) = plt.subplots(1,2, figsize=(8,5), sharex = True)

是一行两列,所以sharex没有意义。

而ax1,ax2是子图,因此无需再次初始化它们

import pandas as pd
import matplotlib.pyplot as plt

data_loc = 'D:\CSVs\Water_Consumption_In_The_New_York_City.csv'
df = pd.read_csv(data_loc, parse_dates=True)
#editing the population data to be per million
df['New York City Population'] = df['New York City Population']/1000000

fig, (ax1,ax2) = plt.subplots(2, 1, figsize=(8,5), sharex = True)
ax1.plot(df['Year'], df['NYC Consumption(Million gallons per day)'])
ax1.legend(['Water Consumption (Million Gallons per Day)'])

ax2.plot(df['Year'], df['New York City Population'], color='red')
ax2.legend(['Population (In Millions)'])
plt.xlabel('Year')

plt.suptitle('NYC Water Consumption Data', size = 15)
plt.show()