简体   繁体   English

Matplotlib:在一组 arrays 上循环散布 plot,具有一致的散点大小和颜色条

[英]Matplotlib: Scatter plot in a loop over set of arrays with consistent scatter point size and color bar

I am trying to generate a scatter plot using dataframe series x & y and the size of the scatter data point using dataframe series z.我正在尝试使用 dataframe 系列 x 和 y 生成散点图 plot,并使用 dataframe 系列 z 生成散点图数据点的大小。

I should mention that I iterate through a set of each x,y, and z arrays and add the color plot outside the loop.我应该提一下,我遍历了一组 x、y 和 z arrays,并在循环外添加了颜色 plot。

I see that the scatter sizes and color bar are generated at each iteration therefore scatter sizes are not consistent with all data points in the plot and also with the colorbar at the end.我看到每次迭代都会生成散点大小和颜色条,因此散点大小与 plot 中的所有数据点以及末尾的颜色条都不一致。 How do I solve this?我该如何解决这个问题?

fig, ax = plt.subplots()
for x, y, z in arrays_of_xyz:
     splot = ax.scatter(x.to_numpy(), y.to_numpy(),  marker= 'o', s = z.to_numpy(), cmap ='viridis_r', c = z.to_numpy())

fig.tight_layout()
plt.colorbar(splot)
plt.show()

Gautham高瑟姆

Can't see in which way the sizes in the plot are inconsistent.看不出 plot 中的尺寸以何种方式不一致。 The colorbar can be inconsistent if you do not enforce consistent vmin and vmax when calling scatter .如果您在调用scatter时不强制执行一致的vminvmax ,则颜色条可能会不一致。

Can you please try with the following code and tell more about inconsistencies you got:您能否尝试使用以下代码并详细说明您遇到的不一致情况:

import numpy as np
import matplotlib.pyplot as plt

num_sets = 3
colors = ("red", "green", "blue")
num_pts_per_set = 20

xs = np.random.randn(num_sets, num_pts_per_set)
ys = np.random.randn(num_sets, num_pts_per_set)
zs = (
    np.random.rand(num_sets, num_pts_per_set)
    * np.arange(1, num_sets + 1).reshape(-1, 1)
    * 30
)
zmin = zs.min()
zmax = zs.max()

fig, (ax1, ax2) = plt.subplots(ncols=2)

ax1.set_title("Sizes according to z\nColors according to set #")
for i, (x, y, z, clr) in enumerate(zip(xs, ys, zs, colors)):
    ax1.scatter(x, y, marker="o", s=z, c=clr, label=f"Set #{i}")
ax1.legend()

ax2.set_title("Facecolors according to z\nSizes according to set #")
for i, (x, y, z, clr) in enumerate(zip(xs, ys, zs, colors)):
    splot = ax2.scatter(x, y, marker="o", c=z, edgecolors=clr, s=(i+1)*30, vmin=zmin, vmax=zmax, label=f"Set #{i}")
ax2.legend()
fig.colorbar(splot)

plt.show()

散点图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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