Warm tip: This article is reproduced from serverfault.com, please click

python-密谋:创建具有类别x轴抖动和多级轴的散点图

(python - Plotly: Create a Scatter with categorical x-axis jitter and multi level axis)

发布于 2020-11-27 22:19:10

我想制作一个具有多级x轴的图形,如下图所示: 多级散布

import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(
  go.Scatter(
    x = [df['x'], df['x1']],
    y = df['y'],
    mode='markers'
  )
)

但我也想像下一张图片一样在x轴上放置抖动: 在此处输入图片说明

到目前为止,我可以使用下面的代码独立制作每个图形:

import plotly.express as px
fig = px.strip(df,
               x=[df["x"], df['x1']], 
               y="y",
               stripmode='overlay') 

是否可以在一个图中组合抖动和多级轴?

这是用于重现数据集的代码:

import numpy as np
import pandas as pd
import random

'''Create DataFrame'''
price = np.append(
  np.random.normal(20, 5, size=(1, 50)), np.random.normal(40, 2, size=(1, 10))
)
quantity = np.append(
  np.random.randint(1, 5, size=(50)), np.random.randint(8, 12, size=(10))
)

firstLayerList = ['15 in', '16 in']
secondLayerList = ['1/2', '3/8']
vendorList = ['Vendor1','Vendor2','Vendor3']

data = {
  'Width':  [random.choice(firstLayerList) for i in range(len(price))],
  'Length': [random.choice(secondLayerList) for i in range(len(price))],
  'Vendor': [random.choice(vendorList) for i in range(len(price))],
  'Quantity': quantity,
  'Price':  price
}
df = pd.DataFrame.from_dict(data)
Questioner
Daniel Zapata
Viewed
11
S3DEV 2020-11-30 05:59:11

首先-感谢你的挑战!这些天来,Plotly的挑战性问题并不多。

创建具有抖动的散点图的关键元素是:

  • 使用mode: 'box'-创建箱形图,而不是散点图。
  • 设置'boxpoints': 'all'-绘制所有点。
  • 使用'pointpos': 0-将点在x轴上居中。
  • 使用以下方法卸下(隐藏!)晶须盒:
    • 'fillcolor': 'rgba(255,255,255,0)'
    • 'line': {'color': 'rgba(255,255,255,0)'}

DataFrame准备:

此代码仅将主要DataFrame拆分为每个供应商的框架,从而允许使用各自的颜色为每个供应商创建跟踪。

df1 = df[df['Vendor'] == 'Vendor1']
df2 = df[df['Vendor'] == 'Vendor2']
df3 = df[df['Vendor'] == 'Vendor3']

绘图代码:

如果愿意,绘图代码可以使用for-loop。但是,我故意使它更加冗长,以提高清晰度。

import plotly.io as pio

layout = {'title': 'Categorical X-Axis, with Jitter'}
traces = []

traces.append({'x': [df1['Width'], df1['Length']], 'y': df1['Price'], 'name': 'Vendor1', 'marker': {'color': 'green'}})
traces.append({'x': [df2['Width'], df2['Length']], 'y': df2['Price'], 'name': 'Vendor2', 'marker': {'color': 'blue'}})
traces.append({'x': [df3['Width'], df3['Length']], 'y': df3['Price'], 'name': 'Vendor3', 'marker': {'color': 'orange'}})

# Update (add) trace elements common to all traces.
for t in traces:
    t.update({'type': 'box',
              'boxpoints': 'all',
              'fillcolor': 'rgba(255,255,255,0)',
              'hoveron': 'points',
              'hovertemplate': 'value=%{x}<br>Price=%{y}<extra></extra>',
              'line': {'color': 'rgba(255,255,255,0)'},
              'pointpos': 0,
              'showlegend': True})

pio.show({'data': traces, 'layout': layout})

图形:

np.random.seed(73)针对问题中发布的数据集创建代码,使用生成了该图后面的数据。

在此处输入图片说明

评论(TL; DR):

此处显示的示例代码使用较低级别的Plotly API,而不是诸如graph_objects的便利包装express原因是我(个人)认为,对用户“幕后”展示正在发生的事情有所帮助,而不是用便捷包装掩盖底层的代码逻辑。

这样,当用户需要修改图形的更详细信息时,他们将更好地理解Plotly为基础图形引擎(orca)构建lists和dicts。

这个用例是这种推理的一个典型例子,因为它使Plotly超出了其(当前)设计点。