【问题标题】:Python: Plot a bar graph for a pandas data frame with x axis using a given columnPython:使用给定列绘制带有 x 轴的熊猫数据框的条形图
【发布时间】:2017-01-09 17:40:31
【问题描述】:

我想在 Jupyter Notebook 上为以下 pandas 数据框绘制条形图。

      | Month | number
-------------------------
    0 | Apr   |  6.5
    1 | May   |  7.3
    2 | Jun   |  3.9
    3 | Jul   |  5.1
    4 | Aug   |  4.1

我做到了:

%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
trend_df.plot(kind='bar')

如何确保 x 轴在此处实际显示月份?

【问题讨论】:

  • 在导入 matplotlib 之前,请执行%matplotlib inline

标签: python pandas jupyter-notebook python-ggplot


【解决方案1】:

您只需在调用plot 时指定x 和y 即可获得所需的条形图。

trend_df.plot(x='Month', y='number', kind='bar')

给定trend_df

In [20]: trend_df
Out[20]: 
  Month  number
0   Apr     6.5
1   May     7.3
2   Jun     3.9
3   Jul     5.1
4   Aug     4.1

【讨论】:

    【解决方案2】:
    store the data in a csv file.
    
    example i named my file plot.csv
    
        save data in following format in plot.csv
    
    Month,number
    
    Apr,6.5
    
    May,7.3
    
    Jun,3.9
    
    Jul,5.1
    
    Aug,4.1
    
    
    import pandas as pd
    
    import matplotlib.pyplot as plt
    
    import numpy as np
    
    import csv
    
    #first read the data
    data = pd.read_csv('plot.csv',sep=',')
    
    print(data)
    #create  a data frame
    df = data.ix[-5:,['Month','number']]
    #plot
    df.plot(kind = 'bar')
    
    plt.show()
    #for ggplot
    plt.style.use('ggplot')
    
    df.plot()
    
    plt.show()
    

    【讨论】:

    • 在上面的答案中不要在数据中换行
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2020-08-31
    • 2021-09-11
    • 2017-04-18
    • 2016-05-16
    相关资源
    最近更新 更多