How can I create an xy graph using python?

Hello I have the following dataframe:

df = [{'Column1': 1, 'Colunm2': 'A', 'Colunm3': 2}, 
      {'Column1': 2, 'Colunm2': 'A', 'Colunm3': 4},
      {'Column1': 3, 'Colunm2': 'A', 'Colunm3': 1},
      {'Column1': 1, 'Colunm2': 'B', 'Colunm3': 7},
      {'Column1': 2, 'Colunm2': 'B', 'Colunm3': 2},
      {'Column1': 3, 'Colunm2': 'B', 'Colunm3': 9}]

      

How can I plot the XY plot between Column1

and Colunm3

but plotted two distinct lines, one for values Colunm2 = 'A'

and one for values Colunm2 ='B'

?

+3


source to share


3 answers


IIUC:

import pandas as pd
df1 = pd.DataFrame(df)
fig,ax = plt.subplots()
for i,g in df1.groupby('Colunm2'):
    g.plot('Column1','Colunm3',ax=ax,label=i)

      



enter image description here

+3


source


As @ScottBoston pointed out in his comment, there is also sns.pointplot

where the parameter hue

is actually a group.

import sns.apiponly as sns
sns.pointplot('Column1', 'Colunm3', data=DataFrame(df), hue='Colunm2')
plt.ylabel('Colunm3')

      



enter image description here

+2


source


You can try this:

import matplotlib.pyplot as plt

df = [{'Column1': 1, 'Colunm2': 'A', 'Colunm3': 2},
      {'Column1': 2, 'Colunm2': 'A', 'Colunm3': 4},
      {'Column1': 3, 'Colunm2': 'A', 'Colunm3': 1},
      {'Column1': 1, 'Colunm2': 'B', 'Colunm3': 7},
      {'Column1': 2, 'Colunm2': 'B', 'Colunm3': 2},
      {'Column1': 3, 'Colunm2': 'B', 'Colunm3': 9}]

first = [(i["Column1"], i['Colunm3'])  for i in df if i['Colunm2'] == 'A']
second = [(i["Column1"], i['Colunm3']) for i in df if i['Colunm2'] == 'B']


plt.plot([a for a, b in first], [b for a, b in first])
plt.plot([a for a, b in second], [b for a, b in second])

plt.show()

      

+1


source







All Articles