user2512443
user2512443

Reputation: 473

How to plot a tuple as x axis and a list on y axis

Suppose I have a df in the following form

import pandas as pd
import numpy as np
import matplotlib as plt
import matplotlib.pyplot as plt

             col1 
(0, 0, 0, 0)  1          
(0, 0, 0, 2)  2          
(0, 0, 2, 2)  3          
(0, 2, 2, 2)  4          

I want to plot my index in x axis and col1 in y axis.

What I tried

plt.plot(list(df.index), df['col1']) 

However, it generates a plot that is not what I am looking for.

Upvotes: 0

Views: 1490

Answers (1)

JohanC
JohanC

Reputation: 80299

If you give a list of 4-tuples as x for plt.plot(), they are interpreted as 4 line plots, one with the first elements from the tuples, one with the second elements, etc.

You can convert the tuples to strings to show them as such:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'y': [1, 2, 3, 4]}, index=[(0, 0, 0, 0), (0, 0, 0, 2), (0, 0, 2, 2), (0, 2, 2, 2)])
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 3))
ax1.plot(list(df.index), df['y'])
ax2.plot([str(i) for i in df.index], df['y'])
plt.show()

line plot of tuples

Upvotes: 2

Related Questions