如何在 matplotlib 中叠加图形?

How can I overlay graphs in matplotlib?

我使用条形图和 matplotlib 的极坐标投影创建了环。

现在我想在这些环上绘制单个数据点。 使用 plt.plot

效果很好

此外,我想根据源数据不同列的类别对数据点进行颜色编码。这可以很好地使用例如 ax.scatter(df[xcol], df[ycol], c=df.Color)

但是,如果我使用 scatter 函数,绘制的点不会与条形图重叠。这仅适用于 plot 函数。

有谁知道我该如何解决这个问题?

这是我当前的代码:


import numpy as np
import matplotlib.pyplot as plt

# draw 4 rings
#Create plot with polar projection for circle structure
fig, ax = plt.subplots(figsize=(12, 8),
                       subplot_kw=dict(projection='polar'))

# remove axes from plot
plt.axis('off')
# create ring coordinates
theta = np.linspace(0, 2 * np.pi, 768)
r = np.linspace(4, 16, 4)
r_ring1 = r[3]-(r[3]-r[2])/2
r_ring2 = r[2]-(r[2]-r[1])/2
r_ring3 = r[1]-(r[1]-r[0])/2
r_ring4 = r[0]/2


# plot the 4 rings
for i in range(r.shape[0]):
    ax.plot(theta, np.repeat(r[i], theta.shape), '-k', lw=1)

#fill rings with radial bar plots
ax.barh(r_ring4, np.pi *2,  height=r[0], color='#ff46a6')
ax.barh(r_ring3, np.pi *2,  height=r_ring2-r_ring3, color='#aaeb8f')
ax.barh(r_ring2, np.pi *2,  height=r_ring2-r_ring3, color='#a2c4c9')
ax.barh(r_ring1, np.pi *2,  height=r_ring1-r_ring2, color='#5DADE2')

#plotting single data points with plot works
for i in range(5):
    plt.plot(0.15*np.pi+i, r_ring1-0.2, marker='o', markersize=7.0, markeredgewidth=1.5,
                 markerfacecolor='red', markeredgecolor='white')

# plotting with scatter is only visible if ax.barh(r_ring2,...) is removed 
for i in range(5):
    ax.scatter(0.15*np.pi+i, r_ring2-0.2, c='red' )
plt.show() 

结果如下图:

只需使用参数zorder

import matplotlib.pyplot as plt

# draw 4 rings
#Create plot with polar projection for circle structure
fig, ax = plt.subplots(figsize=(12, 8),
                       subplot_kw=dict(projection='polar'))

# remove axes from plot
plt.axis('off')
# create ring coordinates
theta = np.linspace(0, 2 * np.pi, 768)
r = np.linspace(4, 16, 4)
r_ring1 = r[3]-(r[3]-r[2])/2
r_ring2 = r[2]-(r[2]-r[1])/2
r_ring3 = r[1]-(r[1]-r[0])/2
r_ring4 = r[0]/2


# plot the 4 rings
for i in range(r.shape[0]):
    ax.plot(theta, np.repeat(r[i], theta.shape), '-k', lw=1)

#fill rings with radial bar plots
ax.barh(r_ring4, np.pi *2,  height=r[0], color='#ff46a6', zorder=0)
ax.barh(r_ring3, np.pi *2,  height=r_ring2-r_ring3, color='#aaeb8f', zorder=0)
ax.barh(r_ring2, np.pi *2,  height=r_ring2-r_ring3, color='#a2c4c9', zorder=0)
ax.barh(r_ring1, np.pi *2,  height=r_ring1-r_ring2, color='#5DADE2', zorder=0)

#plotting single data points with plot works
for i in range(5):
    plt.plot(0.15*np.pi+i, r_ring1-0.2, marker='o', markersize=7.0, markeredgewidth=1.5,
                 markerfacecolor='red', markeredgecolor='white')

# plotting with scatter is only visible if ax.barh(r_ring2,...) is removed 
for i in range(5):
    ax.scatter(0.15*np.pi+i, r_ring2-0.2, c='black', zorder=1)
plt.show()