【问题标题】:Values showing on both x-axes even though plt.subplots(sharex = True)即使 plt.subplots(sharex = True) 也显示在两个 x 轴上的值
【发布时间】:2019-04-10 11:11:18
【问题描述】:

我正在处理一个关于用水量的小型数据集。我有两个子图,我告诉他们分享他们的 x 轴,但是,这些图表并不代表这个事实。在不使用此数据集时,我可以将 plt.subplots(sharex = True) 用于绘图,这让我想知道这是否是 pandas 和 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 轴:

提前谢谢你

【问题讨论】:

    标签: python pandas dataframe matplotlib


    【解决方案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()
    

    【讨论】:

    • 非常感谢,两次初始化它们是问题的原因。赞赏!
    猜你喜欢
    • 2022-12-12
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多