如何从包含许多工作表的 Excel 文件创建比较图

How to create a comparison plot from an Excel file with many worksheets

我想创建一个图表,在 x 轴上显示月份,对于每个国家/地区,它将显示每月的订单。


正在尝试创建一个读取 excel 文件并能够使用 *args 作为参数支持任意数量国家的函数。然后,它应该遍历最终用户可能给出的国家并创建一个比较图。

将导入的 excel 示例:

spain = {'Country': ['Spain', 'Spain', 'Spain', 'Spain', 'Spain', 'Spain', 'Spain', 'Spain', 'Spain', 'Spain', 'Spain', 'Spain'],
         'Month': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
         'Temp': [10, 11, 13, 16, 21, 26, 29, 29, 25, 20, 16, 12],
         'Records': [7, 8, 8, 7, 7, 8, 10, 11, 8, 7, 7, 7],
         'Orders': [70, 70, 66, 60, 58, 50, 43, 43, 54, 63, 69, 70]}

函数参数注意事项如下:

  1. file是xls文件的路径
  2. month 是包含 months
  3. 的 xls 的 Month 列
  4. 是excel
  5. 的订单列
  6. *countries 将是用户可能搜索的任意数量的国家(位于屏幕截图中显示的 xls 的每个 sheet 中)并且会在剧情中进行比较。

注意:图中的 x_axis 将是 个月 并且图中的每一行将显示每个国家每个月的订单数。

这是我创建的,但它不能正常工作。

import matplotlib.pyplot as plt
import pandas as pd

def PlotDataPerMonth(file,month,column,*countries):
    for i in range(len(countries)): # count based on the given countries that have been given
        data = pd.read_excel(file) # Using pd.read_excel() is required
        print(data)


    for name, data in data.groupby('countries'):
        plt.plot(data[month], data[column], label=countries) # month should be the 'month' column 
        plt.xlabel('Months')
        plt.ylabel('Number of Orders')
        plt.legend()
        plt.show()
    
    

有实际数据的函数:

PlotDataPerMonth('Book1.xlsx','Month','Orders',['Spain','Italy'])
  • 没有必要将 'Month' 传递给函数,因为它将始终是 x-axis.
  • pd.read_excel(file, sheet_name=None) 创建一个数据帧字典;每个工作表一对 key-value。
    • 所有工作表的格式应相似。
  • 已包含条形图选项,因为它更适合比较离散值。此数据是离散的,不是连续的。
  • 查看代码解释的内联注释
  • 测试于 python 3.10pandas 1.4.2matplotlib 3.5.1
import calendar

def PlotDataPerMonth(file: str, y_col: str, countries: list, bar: bool=True):
    
    # read in all of the coutry tabs into a dict of dataframes, and them concat them into a single dataframe
    df = pd.concat(pd.read_excel(file, sheet_name=None)).reset_index(drop=True)
    
    # create a list ordered month names from the calendar module
    months = calendar.month_name[1:]
    
    # set the months as ordered and categorical so they will be plotted in order
    df.Month = pd.Categorical(df.Month, months, ordered=True)
    
    # select the countries
    df = df[df.Country.isin(countries)]
    
    # reshape the dataframe for plotting
    dp = df.pivot(index='Month', columns='Country', values=y_col)
    
    # bar plot or line plot
    if bar:
        kind='bar'
    else:
        kind='line'
        
    axe = dp.plot(kind=kind, figsize=(12, 8))
    
    if not bar:
        # set the xticks to show all the labels
        axe.set_xticks(ticks=range(len(dp.index)), labels=months)


# function call
PlotDataPerMonth('Book1.xlsx', 'Orders', ['Spain', 'Italy'], False)
  • 由于数据相同,因此线条彼此重叠

PlotDataPerMonth('Book1.xlsx', 'Orders', ['Spain', 'Italy'])