Plotting dataframe where headers are 24h timestamps

Viewed 79

I have a CSV which looks something like:

0        1       2       3       4       5       6       7       8       9      10      11      12      13      14      15      16      17      18      19      20      21      22      23      24
<>                                                                                                                                                                                                
Red   2151.0  1966.0  1889.0  2148.0  2112.0  2351.0  1813.0  2008.0  1841.0  1901.0  2373.0  2643.0  2322.0  1901.0  1849.0  2132.0  1877.0  1963.0  1861.0  1973.0  2468.0  3434.0  3159.0  3413.0
Blue  2122.0  2059.0  2274.0  2647.0  2136.0  2271.0  2107.0  2192.0  2403.0  2148.0  2008.0  2111.0  2061.0  2196.0  2165.0  2354.0  1931.0  2195.0  1985.0  2025.0  2463.0  2943.0  3302.0  3424.0

I need to plot this data as a scatter plot, where Red/Blue is on the X-axis, and time on the Y-axis. Here 1->24 is timestamps per hour. I am confused as usually we have a timestamp per row, but in my situation, I have to plot each row, for each timestamp.

I then have multiple such CSVs, and will need to plot all of them to one graph.

So my question is, what's the best way to plot all values of Red/Blue for each given timestamp?

When I try to do:

x = sorted_df.index
y = list(sorted_df.columns)


plt.scatter(x, y)
plt.show()

I get a ValueError: x and y must be the same size - and this is my main source of confusion because x and y will never be the same. In the above example, x will always be 2 and y will always be 24!

Any help is much appreciated!

1 Answers

Maybe you could transpose (.T, short for .transpose) your dataframe, iterate its (now) columns and add the scatter plot of each column ("Red", "Blue", etc.) in the same plot:

# Assuming that your index is ["Red", "Blue", ...]
# Assuming that your columns are [1, 2, ...]
sorted_df = sorted_df.T
# Now your index is [1, 2, ...] and columns are ["Red", "Blue", ...]

for column in sorted_df.columns:
    # x: [1, 2, ...] (always the same)
    # y: Values for each column (first "Red", then "Blue", and so on)
    plt.scatter(sorted_df.index, sorted_df[column])

# Display plot
plt.show()

This is the result I get:

Scatter plot from sample data

Related