没有找到标记的对象,并且xticks不会像多个子图一样旋转

时间:2017-06-24 06:28:38

标签: python matplotlib plot

我正在使用plt.subplots创建4个子图。有几个问题:

  1. 虽然我给了标签,但没有找到标签对象。如果我绘制单个情节,没有错误。
  2. xticks不会像左下图那样旋转多个子图。
  3. enter image description here 有什么建议吗?谢谢。

        import matplotlib.pyplot as plt
    
        city_list = ["New York", "Atlanta", "Los Angeles","Chicago"]
        nrows = 2
        ncols = 2
        fig, axes = plt.subplots(nrows, ncols, sharex=True, sharey=True)
        axes_list = [item for sublist in axes for item in sublist] 
    
    
    
       for i in range(len(city_list)):
           df = df1.loc[df1['city_name'] == city_list[i]]
           city_str = city_list[i]
    
           ax = axes_list.pop(0)
           ax.plot_date(df["local_date"], df["product_cnt"], '-',label = 'product_cnt')
           ax.plot_date(df["local_date"], df["usr_cnt"], '-',label = 'user_cnt')
           plt.legend(loc='upper left')
           plt.xticks(rotation=90)
    
           ax.set(title= city_str, ylabel='count', xlabel='Time')
           ax.autoscale_view()
       plt.savefig('DailyCnt.pdf', bbox_inches='tight')
       plt.show()
    

1 个答案:

答案 0 :(得分:1)

您想要处理各自的轴对象。因此,plt.legend()使用ax.legend()而不是ax,而import matplotlib.pyplot as plt import numpy as np import pandas as pd city_list = ["New York", "Atlanta", "Los Angeles","Chicago"] n=30 cn = np.array([[c]*n for c in city_list]).T.flatten() ld = np.repeat(pd.date_range("2012-01-01", periods=n, freq="2M"), len(city_list)) a = np.cumsum(np.random.normal(size=(len(city_list),n)), axis=1).flatten().astype(int) b = np.cumsum(np.random.normal(size=(len(city_list),n)), axis=1).flatten().astype(int) df = pd.DataFrame({'city_name':cn,"local_date":ld, "product_cnt": a, "usr_cnt":b }) nrows = 2 ncols = 2 fig, axes = plt.subplots(nrows, ncols, sharex=True, sharey=True) for i in range(len(city_list)): df1 = df.loc[df['city_name'] == city_list[i]] city_str = city_list[i] ax = axes.flat[i] ax.plot_date(df1["local_date"], df1["product_cnt"], '-',label = 'product_cnt') ax.plot_date(df1["local_date"], df1["usr_cnt"], '-',label = 'user_cnt') ax.legend() plt.setp(ax.get_xticklabels(), rotation=90) ax.set(title= city_str, ylabel='count', xlabel='Time') ax.autoscale_view() plt.tight_layout() #plt.savefig('DailyCnt.pdf', bbox_inches='tight') plt.show() 是相应的轴。您还想旋转相应轴的xticklabels而不是最后一个子图的那些。

jQuery('html, body').animate({
     scrollTop: jQuery("#tabbed").offset().top                               
}, 2000);

enter image description here