Search code examples
pythonpandasmatplotlibbubble-chart

How to build a "scatter-bubble" chart


Newbie on MatPlotLib here!

The following Pandas DataFrame is a simplification of the real one, which has more years and much more events:

df = pd.DataFrame({
    'Year': [2016, 2017, 2018, 2019, 2020],
    'Event 1': [1, 0, 4, 5, 2],
    'Event 2': [2, 0, 0, 1, 2],
    'Event 3': [5, 0, 4, 5, 2],
    'Event 4': [7, 3, 1, 2, 1],
    'Event 5': [0, 2, 0, 4, 5],
})

How to build a chart similar to the following using MatPlotLib?

Scatter-bubble example

Bubble sizes correspond to the occurence values (cell values).


Solution

  • Here's one way:

    df1 = df.melt(id_vars= 'Year')
    sns.scatterplot(x = 'Year', y = 'variable', size = 'value', hue ='variable', data = df1)
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    

    OUTPUT:

    enter image description here