MatPlotLib explode largest array value

Viewed 1167

I am creating an array of song BPMs (Beats Per Minute) and would like to explode the largest bpm regardless of where it falls in the array. I am using python and matplotlib, does anyone know to set this up?

example code below

import numpy as np
import matplotlib 
from matplotlib import pyplot as plt

beat = np.array([180,33,46,76,88,222])

plt.pie(beat, explode=explode)
plt.show
2 Answers

You can use the following one liner solution within the plot command itself

plt.pie(beat, explode=(beat == max(beat)) * 0.1)

Explanation

The line (beat == max(beat)) will result in an array of booleans which will be True where the array will have its maximum

array([False, False, False, False, False, True])

You then multiply it with an explode factor (say 0.1) which will give the following array which you can directly pass to the explode argument

array([0. , 0. , 0. , 0. , 0. , 0.1])

np.argmax can find the index of the largest beat. Then this index can be used to set an explode factor.

import numpy as np
import matplotlib
from matplotlib import pyplot as plt

beat = np.array([180, 33, 46, 76, 88, 222])
explode = np.zeros(len(beat))
explode[beat.argmax()] = 0.1
plt.pie(beat, labels=beat, explode=explode)
plt.show()

resulting plot

Related