0

I want to read an Excel file, sum the values for the years 2021, 2020 and 2019 for the locations from the same region (region B) and then create a graph with two lines (for region A and B) which will show how the values for both regions have changed during the years.

I tried with this code:

import matplotlib.pyplot as plt
import pandas as pd

excel_file_path = "Testfile.xlsx"
df = pd.read_excel(excel_file_path)

x = ["2021", "2020", "2019"]    

y1 = df_region["Values2021"]
y2 = df_region["Values2020"]
y3 = df_region["Values2019"]

fig = plt.figure(figsize=(20,5))

plt.plot(x, y1, color = 'red', label = "A")
plt.plot(x, y2, color = 'blue', label = "B")

plt.legend(loc='best')

plt.show()

But it isn't working for me - I get the following error:

"Exception has occurred: ValueError x and y must have same first dimension, but have shapes (3,) and (2,)"

What do I need to do to get the result that I want? Any help would be greatly appreciated.

1 Answer 1

1

I think you meant to define your y1 and y2 a little differently.

x = ["2021", "2020", "2019"]

fig = plt.figure(figsize=(20,5))
colors = ['red', 'blue']

for i, region in enumerate(df_region.index):
    y = df_region.loc[region, :]
    plt.plot(x, y, color = colors[i], label = region)

plt.legend(loc='best')

plt.show()

which plots AND reads the region names from the DataFrame.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you but I want to read the names of the regions (A or B) directly from the Excel file without defining them inside my code. Do you know how to do this?
Ok. I edited the code to read the region names directly from the DataFrame. If you have more region names, you'll have to provide more colors in the color list. If the result answers your question, please mark the solution as accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.