Home > Software design >  matplotlib bar plot looks cutoff
matplotlib bar plot looks cutoff

Time:12-27

i have a list of values representing 8 distributions.

When i run this code:

            for pidx in range(len(names)):
              name = names[pidx]
              ber = stm_df.loc[x, name].tolist()
              mx_ber = max([mx_ber]   ber)
              mn_ber = min([mn_ber]   ber)
              ber[0] = 0
              sr = pd.Series(ber,x)
              sr = sr[sr > 0]
              rect = axes[1].plot(sr.index, sr.values)

It looks as it should:

enter image description here

But, when i change from ".plot" to ".bar" they all look cutoff Code:

            for pidx in range(len(names)):
              name = names[pidx]
              ber = stm_df.loc[x, name].tolist()
              mx_ber = max([mx_ber]   ber)
              mn_ber = min([mn_ber]   ber)
              ber[0] = 0
              sr = pd.Series(ber,x)
              sr = sr[sr > 0]
              rect = axes[1].bar(sr.index, sr.values)

Results:

enter image description here

Everything else is the same. What is going on?

CodePudding user response:

It is hard to say with the info at hand, but I believe that the height parameter of your bar() may not be properly configured. The height should be configured as the max point of each distribution.

CodePudding user response:

If your goal is to color the area under your distribution curve, I would recommend using plt.fill_between as below.

# Color area under curve 
from matplotlib import pyplot as plt
import numpy as np

# Get x values of the curve (a sine wave in this case)
time = np.arange(0, 10, 0.1);

# Amplitude of the sine wave across time
amplitude = np.sin(time)

# Plot a curve with time and amplitude
plt.plot(time, amplitude, color='black')

# title
plt.title('Sine wave')

# x axis label
plt.xlabel('Time')

# y axis label
plt.ylabel('Amplitude')

# add midline
plt.axhline(y=0, color='k')¨

# fill area between midline across time and amplitude 
plt.fill_between(time, amplitude, color='cyan')

plt.show()

enter image description here

In your example, this would mean simply adding plt.fill_between(sr.index, sr.values, color=f'C{pidx}).

        for pidx in range(len(names)):
          name = names[pidx]
          ber = stm_df.loc[x, name].tolist()
          mx_ber = max([mx_ber]   ber)
          mn_ber = min([mn_ber]   ber)
          ber[0] = 0
          sr = pd.Series(ber,x)
          sr = sr[sr > 0]
          rect = axes[1].plot(sr.index, sr.values)
          plt.fill_between(sr.index, sr.values, color=f'C{pidx})
  • Related