Python 创建直方图并了解maplotlib轴和子图

Python 创建直方图并了解maplotlib轴和子图,python,datetime,matplotlib,Python,Datetime,Matplotlib,我刚刚拼凑matplotlib文档时遇到了一些问题,特别是对于我的数据集。我想我有一个足够小的代码块,它显示了我在阅读文档的同时对所有内容的理解不足。我试图用作参考的文档最初是用于创建线图的 我一直在尝试绘制一个numpy数组,post\u records包含两列。我正在处理社交媒体数据,所以第一列是关于post\u id,第二列是关于datetime\u obj\u col,我使用一些脚本从csv文件中读取了这些数据 我设法在matplotlib中用这些数据创建了一个折线图,但我不太知道如何制

我刚刚拼凑matplotlib文档时遇到了一些问题,特别是对于我的数据集。我想我有一个足够小的代码块,它显示了我在阅读文档的同时对所有内容的理解不足。我试图用作参考的文档最初是用于创建线图的

我一直在尝试绘制一个numpy数组,
post\u records
包含两列。我正在处理社交媒体数据,所以第一列是关于
post\u id
,第二列是关于
datetime\u obj\u col
,我使用一些脚本从csv文件中读取了这些数据

我设法在matplotlib中用这些数据创建了一个折线图,但我不太知道如何制作直方图

现在,当我运行我的程序时,没有显示任何内容

    fig, ax = plt.subplots()
    hist, bins, patch_lst = ax.hist(post_records[:,1], bins=range(31)) # thought that bins could be a sequence, wanted to create 31 bins for 31 total days in a month
    ax.plot(hist, bins)
    ax.set_xlabel('Days')
    ax.set_ylabel('frequency')
    ax.set_title(r'Histogram of Time')

    plt.show() # shows nothing
  • 我需要传递什么到ax.plot?我不清楚如何传入我的x数据集
    • 为什么窗户不露出来
使用如何复制此内容进行编辑:

def create_dataframe_of_datetime_objects_and_visualize():
  datetime_lst = [1521071920000000000, 1521071901000000000, 1521071844000000000, 1521071741000000000, 1521071534000000000] # to get this variable  I loaded my original dataframe with 1980000, sliced the first 5 entries, then printed out the 'datetime_obj_col'. I can't exactly remember what this format is called, I think it's unix time.
  id_lst = [974013, 974072, 327212, 123890, 438201]

  for each in range(len(datetime_lst)):
    datetime_lst[each] = pd.to_datetime(datetime_lst[each], errors='coerce')
    datetime_lst[each] = datetime_lst[each].strftime("%d-%b-%y %H:%M:%S")
    datetime_lst[each] = pd.to_datetime(datetime_lst[each], errors='coerce', dayfirst=True, format="%d-%b-%y %H:%M:%S")
  datetime_lst = pd.Series(datetime_lst)

  df = pd.DataFrame({'tweet_id':id_lst, 'datetime_obj_col': datetime_lst})
  gb_var = df.groupby(df["datetime_obj_col"].dt.month)
  gb_var_count = gb_var.count()
  gb_var.plot(kind="bar")
  plt.show()
请注意,我不再使用直方图。但会出现以下两个错误:

回溯(最近一次呼叫最后一次): 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\core \groupby\groupby.py”,第918行,应用 结果=self.\u python\u apply\u general(f) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\core \groupby\groupby.py”,第936行,在python\u apply\u general中 自平衡轴) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\core \groupby\groupby.py”,第2273行,应用 res=f(组) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\core \groupby\groupby.py“,第541行,在f中 返回自绘制(*args,**kwargs) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\plot ting_core.py”,第2941行,在调用中 排序列=排序列,**kwds) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\plot ting_core.py”,第1977行,在绘图框中 **kwds) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\plot ting_core.py”,第1804行,在图中 绘图对象生成() 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\plot ting_core.py”,第266行,在“生成” self.\u post\u plot\u logic\u common(ax、self.data) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\plot ting_core.py”,第405行,在后绘图逻辑公共中 self.\u应用\u轴属性(ax.yaxis,fontsize=self.fontsize) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site packages\pandas\plot ting_core.py”,第478行,在“应用轴”属性中 labels=axis.get_majorticklabels()+axis.get_minorticklabels() 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ 轴.py”,第1245行,在get_majorticklabels中 ticks=self.get_major_ticks() 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ 轴.py”,第1396行,在get_MARGY_记号中 numticks=len(self.get\u major\u locator()) 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ dates.py”,第1249行,在调用中 self.refresh() 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ dates.py”,第1269行,刷新 dmin,dmax=self.viewlim_to_dt() 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ dates.py”,第1026行,在viewlim_至_dt中 .格式(vmin)) ValueError:视图限制最小值0.0小于1,并且是无效的Matplotlib d 吃价值。如果将非日期时间值传递给h轴,则通常会发生这种情况 作为日期时间单位

编辑:

这看起来像是一个bug,专门与试图使用hist()绘制一列datetime对象有关

我从
post_records
中获取数据,这是一个加载的numpy数组,存储了198000多个post id和datetime对象的二维数据集

这是名为create datetime objects的函数的代码。它打开一个csv文件“tweet\u time\u info\u preprocessed.csv”,该文件只有三列:“tweet\u id”“
tweet\u created\u at\u date
,”和“
tweet\u created\u at\u hour.
“以下代码使用
pandas
library
to\u datetime()
方法将
tweet\u created\u at\u date
tweet\u created\u at\u hour
列组合成格式化的datetime对象

Csv文件示例

然后我有了
visualize\u objects\u histogram()

因此,我将数据帧的5行切掉,并将它们存储到
df_slice
中。我运行此代码时,会出现一个空白的白色窗口。打印
df_切片

                  tweet_id     datetime_obj_col
   0  974072352958042112  2018-03-14 23:58:40
   1  974072272578166784  2018-03-14 23:58:21
   2  974072032177598464  2018-03-14 23:57:24
   3  974071601313533953  2018-03-14 23:55:41
   4  974070732777914368  2018-03-14 23:52:14

还有一个错误信息出现在空白的白色窗口中。它很长

Tkinter回调中的异常 回溯(最近一次呼叫最后一次): 文件“C:\Users\biney\AppData\Local\Programs\Python\Python36-32\lib\tkinter\uu\i nit_uuuuuy.py”,第1699行,在调用中 返回self.func(*args) 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ 后端_backend_tk.py”,第227行,调整大小 self.draw() 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ 后端\backend_tkagg.py“,第12行,在绘图中 超级(FigureCanvasTkAgg,self).draw() 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ 后端\backend_agg.py“,第433行,在绘图中 self.figure.draw(self.renderer) 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ 艺术家.py“,第55行,在draw_包装中 返回绘制(艺术家、渲染器、*args、**kwargs) 文件“C:\Users\biney\AppData\Roaming\Python36\site packages\matplotlib\ 图.py”,图纸中第1475行 渲染器、自身、艺术家、自身(合成) 文件“C:\Users\biney\AppData\Roaming\Python\Python36\site pa
def visualize_objects_histogram():
    print("Visualizing timeplot as histogram")
    post_records= np.load("tweets_and_datetime_objects.npy")
    df = pd.DataFrame(data=post_records, columns=['post_id', 'datetime_obj_col'])
     df_sliced = df[0:5]
     print(df_sliced)
     fig, ax = plt.subplots()
     hist, bins, patch_lst = ax.hist(df_sliced['datetime_obj_col'], bins=range(5))
     ax.plot(hist, bins)
     ax.set_xlabel('Days')
     ax.set_ylabel('frequency')
     ax.set_title('Histogram of Time')

     plt.show()
                  tweet_id     datetime_obj_col
   0  974072352958042112  2018-03-14 23:58:40
   1  974072272578166784  2018-03-14 23:58:21
   2  974072032177598464  2018-03-14 23:57:24
   3  974071601313533953  2018-03-14 23:55:41
   4  974070732777914368  2018-03-14 23:52:14
     def visualize_datetime_objects_with_pandas():
tweets_and_datetime_objects = np.load("tweets_and_datetime_objects.npy") # contains python datetime objects
print("with pandas")
print(tweets_and_datetime_objects.shape)
df = pd.DataFrame(data=tweets_and_datetime_objects, columns=['tweet_id', 'datetimeobj'])
pandas_freq_dict = df['datetimeobj'].value_counts().to_dict()
#print(pandas_freq_dict)
print(len(list(pandas_freq_dict.keys())))
print(list(pandas_freq_dict.keys())[0])
print(list(pandas_freq_dict.values())[1])

plt.plot(pandas_freq_dict.keys(), pandas_freq_dict.values())

#df = df.set_index('datetimeobj')
# changing the index of this dataframe to a time index
#df['datetimeobj'].plot(kind='line', style=['--'])

plt.show()
     date-time temporal data visualization script