Home > Enterprise >  How can I avoid color overlap in matplot python?
How can I avoid color overlap in matplot python?

Time:05-20

I am trying to make a clear visualizatin of my data. This is my code:

width = 0.5
plt.figure(figsize=(10,8))
counts1, bins, bars = plt.hist(data=df1_small, x='fz', bins=np.arange(-5, 5.5, width), color='dodgerblue', alpha=0.3) #rwidth can change the space between bars
#plt.plot(bins[:-1]   width/2, counts1, color='#FF6103', linewidth=2)
counts2, bins, bars = plt.hist(data=df2_big, x='fz', bins=np.arange(-5, 5.5, width), color='red', alpha=0.1)
#plt.plot(bins[:-1]   width/2, counts2, color='#76EEC6', linewidth=2)
labels = ["small", "big"]
plt.legend(labels)
plt.grid(False)
#plt.savefig("./figure/acce.eps", dpi=300)
plt.savefig("./figure/acce.png", dpi=300)
plt.show()

Whenever I plot, I found that color is overlapped if plot is overlapped.

Is there any idea to avoid this overlap?

This is my plot right now: enter image description here

I want to avoid color overlapping and make it clear with just two colors.

Thank you

CodePudding user response:

If you want to avoid any overlap between the two histograms, you could plot both in separate subplots. In this case, I think it makes more sense to title the axes than to add labels, but you could do either. See below:

# Create two subplots, aligned horizontally
fig, axes = plt.subplots(1, 2, figsize=(10, 8))

width = 0.5

# Plot each histogram in its own axis
counts1, bins, bars = axes[0].hist(data=df1_small, x='fz', bins=np.arange(-5, 5.5, width), color='dodgerblue', alpha=0.3) #rwidth can change the space between bars
counts2, bins, bars = axes[1].hist(data=df2_big, x='fz', bins=np.arange(-5, 5.5, width), color='red', alpha=0.1)

# Add title
axes[0].set_title("small")
axes[1].set_title("small")

# Add labels
axes[0].legend("small")
axes[1].legend("big")

# Need to disable the grid for both axes
axes[0].grid(False)
axes[1].grid(False)

plt.savefig("./figure/acce.png", dpi=300)
plt.show()
  • Related