0

I'm trying to make a type of box plot by using this code

import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)    # the x locations for the groups
width = 2       # the height of the bars: can also be len(x) sequence
height = 0.35   # height of bars

D_data = np.array([27.68,np.nan,np.nan])
E_data = np.array([np.nan,18.59,18.31])

fig, ax = plt.subplots()

E = ax.bar(ind, width, height, bottom=E_data-1, label='E')
D = ax.bar(ind, width, height, bottom=D_data-1, label='D')

plt.show()

The graph only outputs the D variable and not the E variable, and I've figured out it's because the first value is np.nan. If I change the first value of E_data to 1, then it works. Is there a way around this?? Is this a problem with the package? Is there a better way to do nan in matplotlib than with numpy? Otherwise it works fine.

0

1 Answer 1

3

You can mask the NaN values using numpy's isfinite() function.

Example:

import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)    # the x locations for the groups
width = 2       # the height of the bars: can also be len(x) sequence
height = 0.35   # height of bars

D_data = np.array([27.68,np.nan,np.nan])
E_data = np.array([np.nan,18.59,18.31])

dmask = np.isfinite(D_data)
emask = np.isfinite(E_data)

fig, ax = plt.subplots()

E = ax.bar(ind[dmask], width, height, bottom=D_data[dmask], label='E')
D = ax.bar(ind[emask], width, height, bottom=E_data[emask], label='D')

plt.show()

Output:

output

1
  • Perfect, this is exactly what I was looking for! Thanks!
    – Ryguy
    Commented Jul 20, 2021 at 23:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.