在下面的示例中,根据要求,每台机器都以自己的颜色绘制,品牌“B”以实线绘制,而其他品牌以虚线绘制。
基本逻辑运行如下:
- 为每台包含
Production 值或None 的机器创建两个numpy 数组,具体取决于Brand 值。
- 此技术使值数组长度保持相等,从而实现正确的 x 轴表示。
- 名称:
- (
b1 (Mach.1, 品牌'B'), o1 (Mach.1, 品牌'other'))
- (
b2(2 马赫,“B”品牌),o2(2 马赫,“其他”品牌))
- 遍历机器 1 的品牌并为每个品牌创建 命名 跟踪。
- 遍历机器 2 的品牌并为每个品牌创建 命名 跟踪。
-
- 绘制图表。
示例代码:
import numpy as np
import pandas as pd
from plotly.offline import iplot
# Copied datasets from SO question.
df1 = pd.read_clipboard()
df2 = pd.read_clipboard()
# Machine 1: Create numpy arrays of values for the given brand.
b1 = np.where(df1['Brand'] == 'B', df1['Production'], None)
o1 = np.where(df1['Brand'] != 'B', df1['Production'], None)
# Machine 2: Same as above.
b2 = np.where(df2['Brand'] == 'B', df2['Production'], None)
o2 = np.where(df2['Brand'] != 'B', df2['Production'], None)
# Setup.
t = []
line = ['solid', 'dash']
brand = ['B', 'Other']
# Machine 1: Create traces for brand B and Other.
for i, Y in enumerate([b1, o1]):
t.append({'x': df1['Day-Shift'],
'y': Y,
'name': f'Machine 1: {brand[i]}',
'line': {'color': 'red',
'dash': line[i]}})
# Machine 2: Create traces for brand B and Other.
for i, Y in enumerate([b2, o2]):
t.append({'x': df2['Day-Shift'],
'y': Y,
'name': f'Machine 2: {brand[i]}',
'line': {'color': 'blue',
'dash': line[i]}})
# Plot the graph.
iplot({'data': t})
图表:
评论(TL;DR):
此处显示的示例代码使用较低级别的 Plotly API,而不是诸如 graph_objects 到 express 之类的便捷包装器。原因是我(个人)觉得展示“幕后”发生的事情对用户很有帮助,而不是用便利的包装器掩盖底层代码逻辑。
这样,当用户需要修改图形的更精细细节时,他们将更好地理解 Plotly 为底层图形引擎(orca)构建的lists 和 dicts。