【问题标题】:How to create a bar graph from csv with dates as the x-axis如何从 csv 创建以日期为 x 轴的条形图
【发布时间】:2012-06-22 13:09:11
【问题描述】:

我想从 csv 文件生成条形图,我的数据如下所示:

06/14/12    SMB 12104560    8096373.6   1.5     1.08
06/15/12    SMB 10328540    8217192.68  1.26    1.24
06/18/12    SMB 5495294     8232792.78  0.67    0.85

我希望第一列是 x 轴,最后一列是 y 轴,如果可能的话,我只想使用最后 5 行数据。这是我迄今为止尝试过的,但是 谢谢

编辑新代码:

data = numpy.loadtxt(StringIO(etf + '.csv' ,dtype= [("date", "S8"), ("value", "f8")]) , usecols=(0,-1))
x = numpy.arange(len(data))
pl1.bar(x,data["value"], width = 0.8)
p1.xticks(x+.4, data["date"])
p1.show()

新错误:TypeError: __init__() got an unexpected keyword argument 'dtype'

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:
    import numpy as np
    from StringIO import StringIO
    import pylab as pl
    
    datastr = """06/14/12    SMB 12104560    8096373.6   1.5     1.08
    06/15/12    SMB 10328540    8217192.68  1.26    1.24
    06/18/12    SMB 5495294     8232792.78  0.67    0.85"""
    
    data = np.loadtxt(StringIO(datastr), 
                      dtype=np.dtype([("date", "S8"), ("value", "f8")]), 
                      usecols=(0,-1))
    x = np.arange(len(data))
    pl.bar(x, data["value"], width=0.8)
    pl.xticks(x+0.4, data["date"])
    pl.show()
    

    【讨论】:

    • 谢谢,但现在我在读取 csv 文件时遇到问题,我收到错误 ValueError: invalid shape in fixed-type tuple。
    • 通过 loadtxt() 读取 csv 文件名:np.loadtxt(etf+'.csv', dtype=...)
    • 并且dtype应该是[("date", "S8"), ('value', 'f8')]
    • TypeError: __init__() got an unexpected keyword argument 'dtype'
    • 从文件中读取,不需要StringIO,只需传递文件名:data = numpy.loadtxt(etf+'.csv' ,dtype= [("date", "S8"), ("value", "f8")], usecols=(0,-1))
    【解决方案2】:

    我不知道 matplotlib 但这可能是问题所在:

    date.append((col[0])) # <- appending a string
    

    也许你应该尝试使用

    ax.set_xticklabels(...)
    

    要获取字符串标签,因为它看起来“日期”列表不应该是字符串。

    【讨论】:

      【解决方案3】:

      对于任何绘图目的,我建议使用 matplotlib。

      有一个简单的example to plot a bar chart - 与您使用的非常相似,但有时从头开始会有所帮助。

      另外,你到底是从哪里得到 TypeError 的?

      关于最后5个元素,你总是可以使用python的列表拼接,例如list[-5:]

      【讨论】:

      • 我正在使用 matplotlib 我无法将日期设为 x 轴。我也在这一行得到类型错误: ax.bar(date,relative, width = 10)
      • 尝试检查所有数组中的数据类型——仅仅因为某些东西是csv中的数字并不意味着读取时不需要转换in
      • 我也试过这样做 (date.append((int((col[0])))) 也没有用
      • 好吧,col[0] 不是一个 int,它是一个字符串,所以你应该在那里添加一个递增的整数。
      猜你喜欢
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 2017-05-06
      相关资源
      最近更新 更多