Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

dataframe - Drawing plot by positions with different colors using python

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.

question from:https://stackoverflow.com/questions/65930306/drawing-plot-by-positions-with-different-colors-using-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...