简体   繁体   中英

How do I keep the smaller value in a bar chart in front (when I cannot place the bars side by side)?

I am plotting two sets of data on a chart that has the amino acid position along the x-axis. Sometimes assay 1 as a smaller value and sometimes assay 2 has the smaller value. How do I ensure that the lower value is always in front?

I am using python and matplotlib / pyplot.

Right now I am adding two bar charts as:

p1 = plot.bar(x1, y1, color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)
p2 = plot.bar(x2, y2, color='b', alpha=1, edgecolor='none', linewidth=0,width=0.5, log=False)

Thanks!

You can use the numpy.ma module to define masks:

import numpy.ma as ma

mask1 = ma.where(y1>=y2)
mask2 = ma.where(y2>=y1)

p1 = plt.bar(x1[mask1], y1[mask1], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)
p2 = plt.bar(x2, y2, color='b', alpha=1, edgecolor='none', linewidth=0,width=0.5, log=False)
p3 = plt.bar(x1[mask2], y1[mask2], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)

Example:

import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma

x1 = x2 = np.arange(5)
y1 = np.array([1,4,25,2,4])
y2 = np.array([4,2,3,32,6])

mask1 = ma.where(y1>=y2)
mask2 = ma.where(y2>=y1)

p1 = plt.bar(x1[mask1], y1[mask1], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)
p2 = plt.bar(x2, y2, color='b', alpha=1, edgecolor='none', linewidth=0,width=0.5, log=False)
p3 = plt.bar(x1[mask2], y1[mask2], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM