如何在 matplotlib 上绘制散点图 python

How to make jitterplot on matplolib python

这是我的代码(改编自here):

df_1 = pd.DataFrame({'Cells' : np.arange(0,100), 'Delta_7' : np.random.rand(100,), 'Delta_10' : np.random.rand(100,), 'Delta_14' : np.random.rand(100,)}, columns = ['Cells','Delta_7', 'Delta_10', 'Delta_14'])



#figure
fig, ax1 = plt.subplots()
fig.set_size_inches(13, 10)



#c sequence
c = df_1['Delta_7']

#plot

plt.scatter(np.full((len(df_1), 1), 1), df_1['Delta_7'] , s = 50, c=c, cmap = 'viridis')
plt.scatter(np.full((len(df_1), 1), 2), df_1['Delta_10'] , s = 50, c=c, cmap = 'viridis')
plt.scatter(np.full((len(df_1), 1), 3), df_1['Delta_14'] , s = 50, c=c, cmap = 'viridis')
cbar = plt.colorbar()

我想用 matplotlib 制作一个漂亮的抖动图(比如 R or seaborn)。问题是我想根据每个单元格的 'Delta_7' 值给每个单元格一种颜色。在绘制 'Delta_10' 和 'Delta_14' 时会保留这种颜色,而我在 seaborn 中没能做到这一点。 如果您有任何线索(python 包、编码技巧……),请告诉我好吗?

此致,

点的位置可以从scatter返回的列表中得到。这些位置可能会抖动,例如仅在 x 方向上。可能 x 轴的范围需要扩大一点以显示每个移位的点。

下面是一些开始实验的代码:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

def jitter_dots(dots):
    offsets = dots.get_offsets()
    jittered_offsets = offsets
    # only jitter in the x-direction
    jittered_offsets[:, 0] += np.random.uniform(-0.3, 0.3, offsets.shape[0])
    dots.set_offsets(jittered_offsets)

df_1 = pd.DataFrame({'Cells': np.arange(0, 100),
                     'Delta_7': np.random.rand(100),
                     'Delta_10': np.random.rand(100),
                     'Delta_14': np.random.rand(100)})
fig, ax1 = plt.subplots()

columns = df_1.columns[1:]
c = df_1['Delta_7']
for i, column in enumerate(columns):
    dots = plt.scatter(np.full((len(df_1), 1), i), df_1[column], s=50, c=c, cmap='plasma')
    jitter_dots(dots)
plt.xticks(range(len(columns)), columns)
xmin, xmax = plt.xlim()
plt.xlim(xmin - 0.3, xmax + 0.3)  # make some room to show the jittered dots
cbar = plt.colorbar()
plt.show()