- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 matplotlib 基于数据框制作步骤图,但我希望显示数据框的键/值之一( signals_df['Gage']
),而不是坐标作为注释,但我总是收到错误:AttributeError: 'Line2D' object has no attribute 'get_offsets'
当我从下到上单击第一个子图并且注释没有出现时。其实我注释掉了annot.set_visible(False)
并替换了 ""
带有 val_gage
的示例,这样当单击子图中的某个点时,它看起来就像我希望注释一个一个地出现。
这是有问题的代码:
import pandas as pd
import numpy as np
import matplotlib as mtpl
from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
annot = mtpl.text.Annotation
data = {
# 'Name': ['Status', 'Status', 'HMI', 'Allst', 'Drvr', 'CurrTUBand', 'RUSource', 'RUReqstrPriority', 'RUReqstrSystem', 'RUResReqstStat', 'CurrTUBand', 'DSP', 'SetDSP', 'SetDSP', 'DSP', 'RUSource', 'RUReqstrPriority', 'RUReqstrSystem', 'RUResReqstStat', 'Status', 'Delay', 'Status', 'Delay', 'HMI', 'Status', 'Status', 'HMI', 'DSP'],
# 'Value': [4, 4, 2, 1, 1, 1, 0, 7, 0, 4, 1, 1, 3, 0, 3, 0, 7, 0, 4, 1, 0, 1, 0, 1, 4, 4, 2, 3],
# 'Gage': ['H1', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H3', 'H1', 'H1', 'H3', 'H3', 'H3', 'H1', 'H3', 'H3', 'H3'],
# 'Id_Par': [0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 0, 0, 22, 22, 28, 28, 28, 28, 0, 0, 38, 38, 0, 0, 0, 0, 0]
'Name': ['Lamp_D_Rq', 'Status', 'Status', 'HMI', 'Lck_D_RqDrv3', 'Lck_D_RqDrv3', 'Lck_D_RqDrv3', 'Lck_D_RqDrv3', 'Lamp_D_Rq', 'Lamp_D_Rq', 'Lamp_D_Rq', 'Lamp_D_Rq'],
'Value': [0, 4, 4, 2, 1, 1, 2, 2, 1, 1, 3, 3],
'Gage': ['F1', 'H1', 'H3', 'H3', 'H3', 'F1', 'H3', 'F1', 'F1', 'H3', 'F1', 'H3'],
'Id_Par': [0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0]
}
signals_df = pd.DataFrame(data)
def plot_signals(signals_df):
print(signals_df)
# Count signals by parallel
signals_df['Count'] = signals_df.groupby('Id_Par').cumcount().add(1).mask(signals_df['Id_Par'].eq(0), 0)
# Subtract Parallel values from the index column
signals_df['Sub'] = signals_df.index - signals_df['Count']
id_par_prev = signals_df['Id_Par'].unique()
id_par = np.delete(id_par_prev, 0)
signals_df['Prev'] = [1 if x in id_par else 0 for x in signals_df['Id_Par']]
signals_df['Final'] = signals_df['Prev'] + signals_df['Sub']
# Convert and set Subtract to index
signals_df.set_index('Final', inplace=True)
# Get individual names and variables for the chart
names_list = [name for name in signals_df['Name'].unique()]
num_names_list = len(names_list)
num_axisx = len(signals_df["Name"])
# Matplotlib's categorical feature to convert x-axis values to string
x_values = [-1, ]
x_values += (list(set(signals_df.index)))
x_values = [str(i) for i in sorted(x_values)]
# Creation Graphics
fig, ax = plt.subplots(nrows=num_names_list, figsize=(10, 10), sharex=True)
plt.xticks(np.arange(0, num_axisx), color='SteelBlue', fontweight='bold')
# Loop to build the different graphs
for pos, name in enumerate(names_list):
# Creating a dummy plot and then remove it
dummy, = ax[pos].plot(x_values, np.zeros_like(x_values))
dummy.remove()
# Get names by values and gage data
data = signals_df[signals_df["Name"] == name]["Value"]
data_gage = signals_df[signals_df["Name"] == name]["Gage"]
# Get values axis-x and axis-y
x_ = np.hstack([-1, data.index.values, len(signals_df) - 1])
y_ = np.hstack([0, data.values, data.iloc[-1]])
y_gage = np.hstack(["", "-", data_gage.values])
# print(y_gage)
# Plotting the data by position
steps = ax[pos].plot(x_.astype('str'), y_, drawstyle='steps-post', marker='*', markersize=8, color='k', linewidth=2)
ax[pos].set_ylabel(name, fontsize=8, fontweight='bold', color='SteelBlue', rotation=30, labelpad=35)
ax[pos].yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
ax[pos].yaxis.set_tick_params(labelsize=6)
ax[pos].grid(alpha=0.4, color='SteelBlue')
# Labeling the markers with Values and Gage
xy_temp = []
for i in range(len(y_)):
if i == 0:
xy = [x_[0].astype('str'), y_[0]]
xy_temp.append(xy)
else:
xy = [x_[i - 1].astype('str'), y_[i - 1]]
xy_temp.append(xy)
# Creating values in text inside the plot
ax[pos].text(x=xy[0], y=xy[1], s=str(xy[1]), color='k', fontweight='bold', fontsize=12)
for val_gage, xy in zip(y_gage, xy_temp):
annot = ax[pos].annotate(val_gage, xy=xy, xytext=(-20, 20), textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(arrowstyle="->"))
# annot.set_visible(False)
# Function for storing and showing the clicked values
def update_annot(ind):
print("Enter update_annot")
coord = steps[0].get_offsets()[ind["ind"][0]]
annot.xy = coord
text = "{}, {}".format(" ".join(list(map(str, ind["ind"]))),
" ".join([y_gage[n] for n in ind["ind"]]))
annot.set_text(text)
annot.get_bbox_patch().set_alpha(0.4)
def on_click(event):
print("Enter on_click")
vis = annot.get_visible()
# print(event.inaxes)
# print(ax[pos])
# print(event.inaxes == ax[pos])
if event.inaxes == ax[pos]:
cont, ind = steps[0].contains(event)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
fig.canvas.mpl_connect("button_press_event",on_click)
plt.show()
plot_signals(signals_df)
我已经测试并审查了许多答案和代码,如下所示:
最佳答案
鼠标悬停在图形数据点上时,使用 Plotly 进行数据注释标签动画
Not to mention a huge slew of other awesome, easy-to-use, widely-compatible JS-interactive graphing capabilities, all free, all in Python. Just install with conda (or pip) no online account required and the plots default to "offline mode" in latest version(s).
plotly
docs,您可以轻松地将这些交互式图表调整为您想要的目的。 .
And through
plotly.express
you still have access to the built-inFig
features relevant to all the other submodules, too. So don't overlook those [e.g., the docs link above shows sections specific for subplotting, custom annnotations/hover annotations, custom style formatting, etc., all which still apply to objects withinplotly.express
!]).
Identical to yours... Plotly is designed to work with
pandas.DataFrames
, specifically*.*(Unlike
matplotlib
— not that it isn't still loved!, just...
well, it's aging rather poorly let's face it.)
import plotly.express as px
import plotly.graph_objs as go
import pandas as pd
import numpy as np
data = {
"Name": [
"Lamp_D_Rq", "Status", "Status", "HMI",
"Lck_D_RqDrv3", "Lck_D_RqDrv3", "Lck_D_RqDrv3",
"Lck_D_RqDrv3", "Lamp_D_Rq", "Lamp_D_Rq",
"Lamp_D_Rq", "Lamp_D_Rq",
],
"Value": [0, 4, 4, 2, 1, 1, 2, 2, 1, 1, 3, 3],
"Gage": [
"F1", "H1", "H3", "H3", "H3",
"F1", "H3", "F1", "F1", "H3",
"F1", "H3",
],
"Id_Par": [0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0],
}
signals_df = pd.DataFrame(data)
注意:然后我跑了
signals_df
通过您的绘图功能,并添加
return signals_df
获取更新的 df,即:
plotly.express
绘制自定义悬停注释(像素)
Here's one relatively (i.e., to
mpl
) quite simple, possible multi-featured, modern interactive display of your data using Plotly (viapx
):
fig = px.line(
signals_df,
y="Value",
x="Sub",
color="Name",
hover_data=["Gage"],
custom_data=["Gage"],
markers=True,
height=500,
render_mode="svg")
fig.update_traces(line={"shape": 'hv'})
fig.update_traces(
hovertemplate="<br>".join([
"Gage: %{customdata[0]}",
])
)
fig.show(config={'displaylogo': False})
关于python - 单击 matplotlib(或可能是 plotly)中的阶梯图子图点时如何使标 checkout 现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69730420/
有没有办法在下面的代码中避免 if..else 条件并在一行中执行此操作? var myObject = {}, data = ["Chennai", "Thoothukkudi", "Mad
我有一个客户想要在他们的主页上使用一个特定的设计来匹配他们在杂志封面上看到的内容。封面的基本阶梯设计从未改变,但图像偶尔会改变。如果不使用 1 个大图像,我无法设计出一种方法来覆盖这种格式。 这是一个
我正在尝试解决 HackerRank 中的一个问题,但我的提交有问题。我的代码在 PyCharm 中有效,但 HackerRank 不接受我的提交。 这是我要解决的问题:https://www.hac
嗨,我是个新手,正在尝试通过 hackerrank 来提高,我正在进行楼梯练习 staircase excercise 但是我的输出与问题不同,因为我的楼梯似乎在结果前面有一个额外的空间,从而使其不正
我正在尝试解决 this使用 std::cout 的 C++ 问题并使用 setw和 setfill 我原来的代码是这样的: void staircase(int n) { for(int i
问题可用here .我的 Python 代码是 def solution(A, B): if len(A) == 1: return [1] ways = [0] *
这是我创建的 IF -Else 阶梯,用于将第一个可见控件聚焦在我的表单上。根据要求,任何控件都可以隐藏在表单上。所以我必须找到第一个可见控件并聚焦它。 if (ddlTranscriptionMe
我正在尝试构建一个系统,用户可以在其中轻松创建各种类型的锦标赛并与其他用户一起参与。它不针对特定游戏,而是一种通用工具,用于在任何设备上尽快查看和更新锦标赛结果,交互最少,因此实际应用程序不会妨碍
我正在使用 ORACLE 数据库,并且正在尝试为以下要求创建 SQL 查询。 以下是我的表快照: ID STATUS ---------- 1 WORKING 1 QUEUIN
我在用, JPA 2.0 Mojarra 2.1.9 JSF 组件库,Primefaces 3.5。 MySQL 5.6.11 我在 MySQL 数据库中有一个名为 state_table 的表以三列
我是一名优秀的程序员,十分优秀!