Drawing plot by positions with different colors using python

Viewed 68

I have a dataframe with 3 columns which I want to make a plot with.

df = pd.DataFrame({
    'position': [100,200,220, 300, 400, 500],
    '1': list('xoooox'),
    '2': list('oxxooo')
})

I drew a scheme below (Sorry for adding am image file, I had difficulties describing it with text)

enter image description here

In the plot, the height of each data doesn't matter. All the bars are the same height

Thank you.

2 Answers

You can do this by passing kind='bar' and color=some_array, for instance:

df = pd.DataFrame({
    'col1': [100, 200, 300, 400],
    'col2': [13, 7, 11, 17],
    'col3': ['r', 'b', 'g', '0.5'],
})

ax = df.plot(x='col1', y='col2', kind='bar', color=df['col3'])

enter image description here

NOTE You can tinker with the style of the plot some more by calling methods on the ax object.

How about using seaborn:

import seaborn as sns

colors = df.groupby(['1','2']).ngroup().astype('category')

sns.barplot(x=df['position'], y=1, hue=colors, dodge=False)

Output:

enter image description here

Or you can manually plot the bars, which allows proper scaling of position:

cmap = {
    ('x','o'): 'b',
    ('o','x'): 'r',
    ('o','o'): 'g',
    ('x','x'): 'm'
}

fig, ax = plt.subplots()
for _, row in df.iterrows():
    ax.bar(row['position'], 1, edgecolor=cmap[(row['1'], row[2])],
           facecolor=(0,0,0,0),
           width=10)

Output:

enter image description here

Related