【问题标题】:While making Plot in pandas python I am getting Error: EOL在 pandas python 中制作 Plot 时出现错误:EOL
【发布时间】:2020-02-18 17:53:33
【问题描述】:

df

import pandas as pd
df = pd.DataFrame({
    'SKU': ['BIKES','MATS', 'BLANKETS', 'CREAMS'],'Col1': [1,3,6,10],'Col2': [4,5, 6,16],'Month':[1,2,3,4],'Year':['2015','2010','2011','2012']})

代码尝试了,但不起作用

    import matplotlib.pyplot as plt

#Visualisations

fig, ax = plt.subplots()
for col in ['Col1', 'Col2']:
    ax.plot(df[col], label=col)
ax.legend(loc="best")
ax.tick_params(axis="x", rotation=30)

我需要几个月的代码和几年的值。但在我可以继续使用代码等之前,我收到了错误:

File "<ipython-input-14-136f7818ccc7>", line 6
    for col in ['Col1', 'Col2']:
                                ^
SyntaxError: EOL while scanning string literal

【问题讨论】:

  • 这一行的引号有误:" ’ ‘ ’ - 你需要" "' '

标签: python pandas plot


【解决方案1】:

您正在打开一种特定类型的撇号并且从不关闭它:

for col in ["Col1', 'Col2']:

需要替换为:

for col in ["Col1","Col2"]:

【讨论】:

    【解决方案2】:
    for col in ['Col1', 'Col2']:
        ax.plot(df['Date'], df[col], label=col) 
    

    【讨论】:

      【解决方案3】:

      您收到错误是因为您没有在 for 循环中给出日期。您需要哪些日期的情节?

      import matplotlib.pyplot as plt
      from matplotlib import dates as mdates
      
      # The new column to be used as x axis
      df['Date'] = pd.to_datetime(df[['Year', 'Month']].assign(Day=1))
      
      # Plot the data
      fig, ax = plt.subplots(figsize=(10, 2))
      for col in ['Col1', 'Col2']:
          ax.plot(df['Date'], df[col], label=col)  #Note I have inserted df['Date'] before df[col] in the code
      ax.legend(loc="best")
      ax.tick_params(axis="x", rotation=30)
      

      在第二次编辑中根据您的要求添加代码:

      years = mdates.YearLocator()    # only print label for the years
      months = mdates.MonthLocator()  # mark months as ticks
      years_fmt = mdates.DateFormatter('%Y')
      
      ax.xaxis.set_major_locator(years)
      ax.xaxis.set_minor_locator(months)
      ax.xaxis.set_major_formatter(years_fmt)
      
      ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-07
        • 1970-01-01
        • 2020-05-23
        • 1970-01-01
        • 2012-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多