【问题标题】:Simple Bar Plot in pythonpython中的简单条形图
【发布时间】:2016-08-14 00:06:42
【问题描述】:

我正在尝试为keyword vs frequency 列表绘制一个简单的bar plot。 由于数据没有header我无法使用PandasSeabron.

输入

#kyuhyun,1
#therinewyear,4
#lingaa,2
#starts,1
#inox,1
#arrsmultiplex,1
#bollywood,1
#kenya,1
#time,1
#watch,1
#malaysia,3

代码:

from matplotlib import pyplot as plt
from matplotlib import*
import numpy as np 

x,y = np.genfromtxt('theri_split_keyword.csv', delimiter = ',', unpack=True, comments=None, usecols=(0,1))

plt.bar(x,y)

plt.title('Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')

plt.show()

我想要绘制的只是一个条形图,其中x axis 作为关键字,y axis 作为频率。任何简单的方法来绘制它都会有很大的帮助。

我得到的输出如下,这绝对不是我想要的。

下面的解决方案似乎很有效,但我的列表中有太多关键字,我正在寻找一个选择,比如我是否只能用各自的关键字绘制前 10-20 个关键字,以便条形图看起来好多了。

答案中给出的解决方案的输出。

【问题讨论】:

    标签: python matplotlib plot graph bar-chart


    【解决方案1】:
        import numpy as np
        import matplotlib.pyplot as plt
        import csv
    
        x = []
        y = []
        with open('theri_split_keyword.csv', "rb") as csvfile:
            reader = csv.reader(csvfile, delimiter=',')
            for row in reader:
                x.append(row[0].lstrip('#'))
                y.append(int(row[1]))
    
        ind = np.arange(len(x))  # the x locations for the groups
        width = 0.35       # the width of the bars
    
        fig, ax = plt.subplots()
        plt.bar(ind,y)
    
        ax.set_ylabel('Y axis')
        ax.set_title('X axis')
        ax.set_xticks(ind + width)
        ax.set_xticklabels(x, rotation='vertical')
    
    
        plt.show()
    

    【讨论】:

    • 嗨 .. 感谢您提供有效的解决方案。但是我在这里似乎有一个问题,关键字列表太大了,我可以采取的任何方式都可能是前 10 - 20 个关键字和尊重频率。我在编辑中包括了最终情节。请建议 thr 是否是选择热门关键字的任何此类选项。
    • @SitzBlogz:如果您还有其他问题,请将其作为单独的问题发布;如果这回答了您最初的问题,请接受。
    【解决方案2】:

    没有回答您的问题,但 pandas 不需要数据有标题。 如果您从文件中读取数据,只需选择 header=None(更多信息here)。

    df = pd.read_csv(myPath, header=None)
    df.columns = ('word','freq') # my cystom header
    df.set_index('word') # not neccesary but will provide words as ticks on the plot
    df.plot(kind='bar')
    

    您也可以将数据作为字典传递,例如

    df = pd.DataFrame({'word':['w1','w2','w3'],'freq':[1,2,3})
    df.plot.bar()
    

    【讨论】:

    • 能否请您提供完整代码,以了解在没有标题时如何使用 pandas 读取列
    【解决方案3】:

    我不熟悉np.genfromtxt,但我怀疑问题是当x 应该是数字时,它会以字符串数组的形式返回x

    也许可以试试:

    tick_marks = np.arange(len(x))
    plt.bar(tick_marks, y)
    plt.xticks(tick_marks, x, rotation=45)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-30
      • 2023-03-29
      • 2010-12-21
      • 2022-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多