【问题标题】:Plotting data using matplotlib from csv but the numbers on the y-axis are not in order使用 csv 中的 matplotlib 绘制数据,但 y 轴上的数字不按顺序排列
【发布时间】:2022-01-04 22:19:58
【问题描述】:

我是 Python 新手,我一直在尝试使用 PyCharm 中的 matplotlib 从 csv 文件绘制图形。 x 轴是月份,y 轴是销售额,但 y 轴上的数字顺序不正确。我读过我需要将其转换为浮点数,但它显示“ValueError:无法将字符串转换为浮点数:'sales'”。我认为这是因为在 csv 文件中,带有销售数据的行的标题是“销售”,所以它不能将“销售”这个词转换为浮动。如何让它忽略标题并将其余值转换为浮点数?或者如果这不是问题所在,有人可以帮我解决吗?:)

这是我的代码(我没有尝试转换为浮点数):

import matplotlib.pyplot as plt

x = []
y = []

with open('sales.csv','r') as sales_csv:
    plots = csv.reader(sales_csv, delimiter=',')
    for row in plots:
        x.append(row[1])
        y.append(row[2])

plt.plot(x, y, color='r', label='Monthly Sales 2018', marker='o')
plt.xlabel('Month')
plt.ylabel('Sales')
plt.title('Monthly Sales 2018')
plt.legend()

plt.show()

请在附件中找到图表外观的屏幕截图。 graph

另外,仅供参考,这是csv文件(只需要绘制月份和销售额)

year, month,sales,expenditure
2018,jan,6226,3808
2018,feb,1521,3373
2018,mar,1842,3965
2018,apr,2051,1098
2018,may,1728,3046
2018,jun,2138,2258
2018,jul,7479,2084
2018,aug,4434,2799
2018,sep,3615,1649
2018,oct,5472,1116
2018,nov,7224,1431
2018,dec,1812,3532

任何帮助将不胜感激!

【问题讨论】:

    标签: python csv matplotlib graph


    【解决方案1】:

    只需将您的数据粘贴到一个文件中并将其保存为test.csv 并运行它。请注意,您的第二列名称是' month' 而不是'month',因为您现在粘贴的数据在第一列之后的逗号后面有一个空格。要么保留它并运行此代码,要么删除它并编辑此代码以将 ' month' 替换为 'month'

    import pandas as pd
    from matplotlib import pyplot as plt
    import matplotlib.dates as mdates
    
    # paste your data into a file and save it as test.csv
    # Please note that read_csv assumes that row 0 is the header, so, 
    # we don't need to pass that argument for your case
    data = pd.read_csv('test.csv') 
    
    data[' month'] = data[' month'].str.title()
    data['Date'] = data[' month']
    # converting type from str to pandas datetime stamps
    data['Date'] = pd.to_datetime(data['Date'], format='%b')
    # changing the year from 1900 (default) to 2018(desired)
    data['Date'] = data['Date'].mask(data['Date'].dt.year == 1900, 
                                 data['Date'] + pd.offsets.DateOffset(year=2018))
    
    plt.plot(data['Date'], data['sales'], color='r', label='Monthly Sales 2018', marker='o')
    
    # x-axis date representation formatting
    myFmt = mdates.DateFormatter('%b')
    plt.gca().xaxis.set_major_formatter(myFmt)
    
    plt.xlabel('Month')
    plt.ylabel('Sales')
    plt.title('Monthly Sales 2018')
    plt.legend()
    plt.show()
    

    您可以在此链接中阅读有关 python 中日期时间行为的更多信息:https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

    【讨论】:

      【解决方案2】:

      由于 CSV 有一个标题,您可以使用csv.DictReader(sales_csv) 来读取您的 CSV 文件。默认情况下,它将读取 CSV 中的第一行作为 CSV 的列名,而不是将其用作常规行。然后,当您遍历行时,您可以使用row["month"]row["sales"] 访问相应的列。

      with open('sales.csv','r') as sales_csv:
          plots = csv.DictReader(sales_csv, delimiter=',')
          for row in plots:
              x.append(row["month"])
              y.append(float(row["sales"]))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-02
        • 2020-05-12
        • 2016-05-12
        • 2021-01-13
        • 2020-10-11
        • 2022-11-30
        • 1970-01-01
        相关资源
        最近更新 更多