Python maxplotlib boxsplot子图+散点图

2024-10-03 11:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在箱线图中执行散点图作为子图。当我只做一个boxsplot时,它就起作用了。我可以在boxsplot内部定义具有特定颜色的特定点。绿色小球(图1)表示与箱线图值相比的特定数字

  for columnName in data_num.columns:
    plt.figure(figsize=(2, 2), dpi=100)
    bp = data_num.boxplot(column=columnName, grid=False)
    y = S[columnName]
    x = columnName
    if y > data_num[columnName].describe().iloc[5]:
      plt.plot(1, y, 'r.', alpha=0.7,color='green',markersize=12)
      count_G = count_G + 1
    elif y < data_num[columnName].describe().iloc[5]:
      plt.plot(1, y, 'r.', alpha=0.7,color='red',markersize=12)
      count_L = count_L + 1
    else:
      plt.plot(1, y, 'r.', alpha=0.7,color='yellow',markersize=12)
      count_E = count_E + 1

图1-散点+1箱线图

我可以使用箱线图创建子图

  fig, axes = plt.subplots(6,10,figsize=(16,16)) # create figure and axes
  fig.subplots_adjust(hspace=0.6, wspace=1)

  for j,columnName in enumerate(list(data_num.columns.values)[:-1]):
    bp = data_num.boxplot(columnName,ax=axes.flatten()[j])

图2-子地块+箱线图
但当我试图在每个箱线图中绘制一个特定的数字时,实际上它订阅了整个图

plt.subplot(6,10,j+1)  
if y > data_num[columnName].describe().iloc[5]:
  plt.plot(1, y, 'r.', alpha=0.7,color='green',markersize=12)
  count_G = count_G + 1
elif y < data_num[columnName].describe().iloc[5]:
  plt.plot(1, y, 'r.', alpha=0.7,color='red',markersize=12)
  count_L = count_L + 1
else:
  plt.plot(1, y, 'r.', alpha=0.7,color='black',markersize=12)
  count_E = count_E + 1

图3-子批次+散点


Tags: alphadataplotcountplt数字numcolor
1条回答
网友
1楼 · 发布于 2024-10-03 11:19:32

究竟出了什么问题还不完全清楚。可能对plt.subplot(6,10,j+1)的调用正在擦除某些内容。但是,在matplotlib的标准现代使用中,这种调用是不必要的,因为子地块是通过fig, axes = plt.subplots()创建的。小心使用ax.plot()而不是plt.plot()plt.plot()在“当前”ax上绘制,当存在大量子地块时,这可能会有点混乱

下面的示例代码首先创建一些玩具数据(希望与问题中的数据类似)。然后,方框图和各个点被画成一个循环。为了避免重复,计数和颜色存储在字典中。由于data_num[columnName].describe().iloc[5]似乎是中位数,为了可读性,代码直接计算该中位数

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

column_names = list('abcdef')
S = {c: np.random.randint(2, 6) for c in column_names}
data_num = pd.DataFrame({c: np.random.randint(np.random.randint(0, 3), np.random.randint(4, 8), 20)
                         for c in column_names})
colors = {'G': 'limegreen', 'E': 'gold', 'L': 'crimson'}
counts = {c: 0 for c in colors}

fig, axes = plt.subplots(1, 6, figsize=(12, 3), gridspec_kw={'hspace': 0.6, 'wspace': 1})
for columnName, ax in zip(data_num.columns, axes.flatten()):
    data_num.boxplot(column=columnName, grid=False, ax=ax)
    y = S[columnName]  # in case S would be a dataframe with one row: y = S[columnName].values[0]
    data_median = data_num[columnName].median()
    classification = 'G' if y > data_median else 'L' if y < data_median else 'E'
    ax.plot(1, y, '.', alpha=0.9, color=colors[classification], markersize=12)
    counts[classification] += 1
print(counts)
plt.show()

example plot

相关问题 更多 >