【问题标题】:How to plot two graphs using matplotlib in python pandas?如何在 python pandas 中使用 matplotlib 绘制两个图?
【发布时间】:2018-02-24 08:52:57
【问题描述】:

我在这个文件中有数据https://drive.google.com/open?id=0B4KXs5bh3CmPWXJkQWhkbzI0WEE

#count weekdays 0 to 4
mUserType = np.where(rides['starttime'].dt.dayofweek <= 5, 'Weekend', 
'Weekday')
#count hours
mWeekHours = rides['starttime'].dt.hour
#create group by usertype
WeekdayWorkdayResult = rides.groupby([mUserType, mWeekHours, 
'usertype']).size().unstack()
WeekdayWorkdayResult

此代码根据用户类型(即客户和订阅者)计算周末和工作日的小时数

我想用 matplotlib 以这种格式绘制图形怎么办?Weekday and Weekend Graph

按小时和用户类型显示乘车次数。一个情节用于工作日,第二个情节用于周末。包括所有每小时骑行的情节线

# count trips by date and by hour

ind = pd.DatetimeIndex(rides.starttime)
rides['date'] = ind.date.astype('datetime64')
rides['hour'] = ind.hour
by_hour = rides.pivot_table('tripduration', aggfunc='count',
                       index=['date', 'hour'],
                       columns='usertype').fillna(0).reset_index('hour')

# average these counts by weekend
by_hour['weekend'] = (by_hour.index.dayofweek >= 5)
by_hour = by_hour.groupby(['weekend', 'hour']).mean()
by_hour.index.set_levels([['weekday', 'weekend'],
                     ["{0}:00".format(i) for i in range(24)]],
                    inplace=True);
by_hour.columns.name = None
fig, ax = plt.subplots(1, 2, figsize=(16, 6), sharey=True)
by_hour.loc['weekday'].plot(title='Hourly Rides User Type and Hour', 
ax=ax[0])
by_hour.loc['weekend'].plot(title='Weekend Rides by User Type and Hour', 
ax=ax[1])
ax[0].set_ylabel('Hourly Rides by User Type');

这是我只获取订阅者和客户数据的代码,我还想获取所有图表线表示周末和工作日的子和客户的小时总和

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以将subplot 用于一个绘图上的多个图表。

    告诉它有多少行和列,以及你正在绘制的内容。 有一个演示here

    import matplotlib.pyplot as plt
    
    
    #set up data
    
    plt.subplot(2, 1, 1) #two rows, one columns, first graph
    #Call plt.plot(x1, y1) with the data you want
    plt.title('First subplot')
    
    plt.subplot(2, 1, 2) #two rows, one columns, 2nd graph
    #Call plt.plot(x2, y2) with the data you want
    plt.title('Second subplot')
    
    plt.show()
    

    【讨论】:

    • 我想按照图片中的方式绘制图表,但无法做到
    • 您能否更明确地说明您尝试了什么以及出了什么问题?你的话表明一张图上​​的两个图是问题所在。
    【解决方案2】:

    这是一个公正的代码,但这就是我的情节

    import matplotlib.pyplot as plt 
    
    plt.plot(x-axis,y-axis,data)
    plt.plot(x-axis,y-axis,data)
    
    plt.show() 
    

    所以之前,如果你绘制两次,两条线将在同一个图中。

    【讨论】:

    • 能否请您使用以上数据绘制图表,因为我无法做到
    猜你喜欢
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 2019-01-15
    相关资源
    最近更新 更多