How to plot observations from each row of a dataframe as a line plot

Viewed 444

I want to display multiple datasets in one graph.

But i can't seem to get the y axis to work and get the following error: ValueError: x and y must have same first dimension, but have shapes (2,) and (6060000,)

Since I am still a beginner and i copied parts of my code from different sources, my code is most likely pretty bad at some places.

I never asked any pandas/matplotlib questions, so i hope this is reproducible.

The dataframe has many columns, but only a small subset have been provided in the code sample.

enter image description here

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd

channel_data = pd.DataFrame({'Creation date': ['2014-01-02', '2013-09-11', '2007-08-19'], 'Subscriber count': [6060000, 4110000, 4440000    ]})

# get x and y from first channel
now = str(dt.datetime.now())
now = now[:10]

dates = [channel_data["Creation date"][0], now]
dates2 = [channel_data["Creation date"][1], now]
dates3 = [channel_data["Creation date"][2], now]
x1 = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates]
x2 = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates2]
x3 = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates3]

# PROBLEM HERE

y1 = range(len(x1)) # i got the x axis to work but am having problems with this part
y2 = range(len(x2))
y3 = range(len(x3))

#y1 = range(0, channel_data["Subscriber count"][0])
# this was my idea of displaying the data (y-axis)
# -----------------------------------------------------------

plt.figure(figsize=(10, 5))
plt.title("Channel growth over time [USD]", fontdict={"fontweight": "bold"})


plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

plt.plot(x1, y1, "b.-", label="Carwow") #b.- to choose color=blue, pointer=. , line=normal line 
plt.plot(x2, y2, "r.-", label="Doug Demuro")
plt.plot(x3, y3, "g.-", label="Scotty Kilmer")

plt.xlabel("Date", fontdict={"fontsize": 13})
plt.ylabel("Subscribers", fontdict={"fontsize": 12})

plt.legend()

plt.show()

enter image description here

enter image description here The first image shows the current graph (with wrong y values). The second image shows a scetch of how i want to display the data.

I know this is a lot to ask at once but maybe just has an idea or a direction which i could go. Tried out a bunch of stuff but nothing worked.

Thank you for reading.

1 Answers
  • As a note, this is not the correct way to visualize growth rate. The plot implies linear growth, because you're just plotting a line between two points. Growth rate should be determine based on the intermediate count on other dates.
  • The error was occurring at plt.plot(x1, y1,...), because x1 was the length d in dates (which is 2), but y1 was a length of 6060000.
  • Use pandas.DataFrame.iterrows to iterate through and plot each observation.
  • Each list for x and y of plot is comprised of 2 values
    • x always begins at the creation date, and ends at now
    • y always begins at 0, and ends at the subscriber count
import pandas as pd
import matplotlib.pyplot as plt

# crate a dataframe
df = pd.DataFrame({'Creation date': ['2014-01-02', '2013-09-11', '2007-08-19'], 'Subscriber count': [6060000, 4110000, 4440000], 'Channel name': ['Carwow', 'Doug Demuro', 'Scotty Kilmer']})

# convert any date columns to a datetime dtype
df['Creation date'] = pd.to_datetime(df['Creation date']).dt.date

# display(df)
  Creation date  Subscriber count   Channel name
0    2014-01-02           6060000         Carwow
1    2013-09-11           4110000    Doug Demuro
2    2007-08-19           4440000  Scotty Kilmer

# get the current datetime date
now = datetime.now().date()

# iterate through the rows and plot
for i, v in df.iterrows():
    
    # get the values and labels to plot
    x0 = v['Creation date']
    y1 = v['Subscriber count']
    label = v['Channel name']

    plt.plot([x0, now], [0, y1], label=label)
    
plt.legend()

enter image description here

Related