小编Fla*_*ino的帖子

如何将文本标签添加到 Python 中的 Plotly 散点图?

我正在尝试在 Python 中的 Plotly 散点图中的数据点旁边添加文本标签,但出现错误。

我怎样才能做到这一点?

这是我的数据框:

world_rank  university_name country teaching    international   research    citations   income  total_score num_students    student_staff_ratio international_students  female_male_ratio   year
0   1   Harvard University  United States of America    99.7    72.4    98.7    98.8    34.5    96.1    20,152  8.9 25% NaN 2011
Run Code Online (Sandbox Code Playgroud)

这是我的代码片段:

citation = go.Scatter(
                    x = "World Rank" + timesData_df_top_50["world_rank"],  <--- error
                    y = "Citation" + timesData_df_top_50["citations"], <--- error
                    mode = "lines+markers",
                    name = "citations",
                    marker = dict(color = 'rgba(48, 217, 189, 1)'),
                    text= timesData_df_top_50["university_name"])
Run Code Online (Sandbox Code Playgroud)

错误如下所示。

TypeError: ufunc 'add' did …
Run Code Online (Sandbox Code Playgroud)

python scatter plotly

4
推荐指数
1
解决办法
1万
查看次数

Plotly Dash:单个单元格的数据表背景颜色

我在dash_table.DataTable数据框中显示,其中有一列颜色名称为十六进制格式,代码如下:

import dash
import dash_table
import pandas as pd

df = pd.DataFrame(data = dict(COLOR = ['#1f77b4', '#d62728', '#e377c2', '#17becf', '#bcbd22'],
                              VALUE = [1, 2, 3, 4, 5]))

app = dash.Dash(__name__)

app.layout = html.Div([dash_table.DataTable(id = 'table',
                                            columns = [{"name": i, "id": i} for i in df.columns],
                                            data = df.to_dict('records'))],
                      style = dict(width = '200px'))

if __name__ == '__main__':
    app.run_server()
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

在此输入图像描述

我想设置每个单元格及其内容的背景颜色(可能还有字体颜色),但仅限于该列(始终是表格的第一列)以获得以下结果:

在此输入图像描述

对我来说可以dash_table.DataTableplotly.graph_objects.Table文档)替换,这也许更可定制;plotly.graph_objects.Table前提是我可以在仪表板中实现dash

版本信息:

Python               3.7.0
dash                 1.12.0
dash-table           4.7.0 …
Run Code Online (Sandbox Code Playgroud)

python datatable background-color plotly-dash

4
推荐指数
1
解决办法
2万
查看次数

如何使用动态时间扭曲获得距离矩阵?

我有 6 个时间序列值,如下所示。

import numpy as np
series = np.array([
     [0., 0, 1, 2, 1, 0, 1, 0, 0],
     [0., 1, 2, 0, 0, 0, 0, 0, 0],
     [1., 2, 0, 0, 0, 0, 0, 1, 1],
     [0., 0, 1, 2, 1, 0, 1, 0, 0],
     [0., 1, 2, 0, 0, 0, 0, 0, 0],
     [1., 2, 0, 0, 0, 0, 0, 1, 1]])
Run Code Online (Sandbox Code Playgroud)

假设,我想获取动态时间扭曲的距离矩阵来执行聚类。我dtaidistance为此使用了库,如下所示。

from dtaidistance import dtw
ds = dtw.distance_matrix_fast(series)
Run Code Online (Sandbox Code Playgroud)

我得到的输出如下。

array([[       inf, 1.41421356, 2.23606798, 0. …
Run Code Online (Sandbox Code Playgroud)

python time-series dtw

4
推荐指数
1
解决办法
2632
查看次数

Plotly:重新标记滑块上的动画刻度线

我正在使用滑块来显示热图动画,并希望重新标记滑块上出现的刻度线。

我的动画中有 50 帧,热图中的每个矩阵的尺寸为 7×7,其中七行/列对应于列表,labels=['A','B','C','D '、'D'、'F'、'G']。此外,在我的应用程序中,每个帧对应于 5 秒的窗口,因此,例如,第 3 帧对应于 15 秒。这是到目前为止我的简单示例,我模仿https://plotly.com/python/sliders/上的文档

import numpy as np
import plotly.graph_objs as go

N = 50
M = np.random.random((N, 7, 7))
labels=['A','B','C','D','D','F','G']
window_length=5

fig = go.Figure()

for step in range(N):
      fig.add_trace(
            go.Heatmap(x=labels,y=labels,z=M[step]))

fig.data[1].visible = True


# Create and add slider
steps = []
for i in range(len(fig.data)):
    step = dict(
        method="update",
        args=[{"visible": [False] * len(fig.data)},
        {"title": "Time: " + str(window_length*i)+' sec'}],)
    step["args"][0]["visible"][i] = True  # Toggle i'th trace to "visible"
    steps.append(step)


sliders …
Run Code Online (Sandbox Code Playgroud)

python plotly

4
推荐指数
1
解决办法
3030
查看次数

尝试在 Plotly Dash 中生成图表时出错

当尝试使用以下代码生成图形时

@app.callback(
    [
        Output("selected-plot", "figure")
    ],
    [
        Input("submit-selected-plotting", "n_clicks"),
        State("table", "data")
    ],
)
def plot(button_clicked, data)           
    fig = go.Scatter(x=data["index"],
                     y=data["result"],
                     mode='lines',
                     name='result')
    return fig
Run Code Online (Sandbox Code Playgroud)

            dbc.Col(
                [
                    dcc.Graph(id='selected-plot')
                ],
                width=6,
            )
Run Code Online (Sandbox Code Playgroud)

我收到一个奇怪的错误,应用程序期待不同的对象:

dash._grouping.SchemaTypeValidationError:架构:[<Output selected-plots.figure>] 路径:() 预期类型:(<class 'tuple'>,<class 'list'>) 收到类型 <class 'plotly.graph_objs._scatter.Scatter' 的值>: 分散({...})

我已经尝试了一切,但似乎无法解决这个错误。感谢您提前提出任何建议!

python plotly plotly-dash

4
推荐指数
1
解决办法
1万
查看次数

Confusion Matrix ValueError: Classification metrics can't handle a mix of binary and continuous targets

I'm currently trying to make a confusion matrix for my neural network model, but keep getting this error:

ValueError: Classification metrics can't handle a mix of binary and continuous targets.
Run Code Online (Sandbox Code Playgroud)

I have a peptide dataset that I'm using with 100 positive and 100 negative examples, and the labels are 1s and 0s. I've converted each peptide into a Word2Vec embedding that was put into a ML model and trained.

This is my code:

pos = "/content/drive/MyDrive/pepfun/Training_format_pos (1).txt"
neg = "/content/drive/MyDrive/pepfun/Training_format_neg.txt" …
Run Code Online (Sandbox Code Playgroud)

python machine-learning neural-network keras tensorflow

4
推荐指数
1
解决办法
1万
查看次数

如何在Python中不使用sklearn计算TPR和FPR?

初始化列表列表:

data = [[1.0, 0.635165,0.0], [1.0, 0.766586,1.0], [1.0, 0.724564,1.0],
        [1.0, 0.766586,1.0],[1.0, 0.889199,1.0],[1.0, 0.966586,1.0],
        [1.0, 0.535165,0.0],[1.0, 0.55165,0.0],[1.0, 0.525165,0.0],
        [1.0, 0.5595165,0.0] ]
Run Code Online (Sandbox Code Playgroud)

创建 Pandas 数据框:

df = pd.DataFrame(data, columns = ['y', 'prob','y_predict']) 
Run Code Online (Sandbox Code Playgroud)

打印数据框。

print(df)
Run Code Online (Sandbox Code Playgroud)

对于这个数据集,我想找到:

  1. 不使用 Sklearn 的混淆矩阵
  2. 不使用 Sklearn 的 TPR 和 FPR 的 Numpy 数组,用于绘制 ROC。

如何在 python 中做到这一点?

python machine-learning roc auc precision-recall

3
推荐指数
1
解决办法
1万
查看次数

Plotly Dash 应用程序中的布局管理:如何定位 html div?

我正在创建一个dash应用程序,这是我的代码:

# import required packages
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import numpy as np
import pandas as pd


# define figure creation function
def create_figure():
    N = 100
    x_min = 0
    x_max = 10
    y_min = 0
    y_max = 10

    blue = '#6683f3'
    orange = '#ff9266'
    grey = '#e0e1f5'
    black = '#212121'

    x = np.linspace(x_min, x_max, N)
    y = np.linspace(y_min, y_max, N)
    XX, …
Run Code Online (Sandbox Code Playgroud)

html css python layout plotly-dash

3
推荐指数
1
解决办法
1万
查看次数

Plotly Dash:如何重置 dash-html.button 的“n_clicks”属性?

我在 plotly/dash 中有一个基本的数据表。我的目标是在按下上传按钮后上传(或为了示例而打印...)。

问题是,我不知道如何将按钮的 n_clicks 属性恢复为零。所以发生的事情是,在我第一次点击按钮后,只要有变化(添加行或更改/添加数字),它就会连续打印,但我想要的是每当我点击按钮时它只打印一次。

这是代码:

import dash
from dash.dependencies import Input, Output, State
import dash_table
import dash_daq as daq

import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']


df = pd.read_csv('.../dummy_csv.csv')


app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div(id='my-div'),

    dash_table.DataTable(
        id='adding-rows-table',
        style_data={
            'whiteSpace': 'normal',
            'height': 'auto'
        },
        style_table={
            'maxHeight': '800px'
            , 'overflowY': 'scroll'
        },
        columns=[
            {'name': i, 'id': i} for i in df.columns
        ],
        data=df.to_dict('records'),
        editable=True,
        row_deletable=True

    ),

    html.Button('+ Row', id='editing-rows-button', n_clicks=0),

    html.Button('Update', …
Run Code Online (Sandbox Code Playgroud)

python plotly-dash

3
推荐指数
1
解决办法
4085
查看次数

Plotly Dash:dash_bootstrap_components.Collapse 不折叠

我正在尝试dash_bootstrap_components.Collapse在我的dash应用程序中实现 a ,但它的行为存在问题。这里的代码,我不是自己写的,我只是从dash_bootstrap_components.Collapse 文档中复制过来的:

import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State

app = dash.Dash()

app.layout = html.Div([dbc.Button('Open collapse',
                                  id = 'collapse-button',
                                  className = 'mb-3',
                                  color = 'primary'),
                       dbc.Collapse(dbc.Card(dbc.CardBody('This content is hidden in the collapse')),
                                    id = 'collapse')])


@app.callback(Output('collapse', 'is_open'),
              [Input('collapse-button', 'n_clicks')],
              [State('collapse', 'is_open')])
def toggle_collapse(n, is_open):
    if n:
        return not is_open
    return is_open

if __name__ == "__main__":
    app.run_server()
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

在此处输入图片说明

当我点击按钮时,没有任何反应。
我试图找出问题出在哪里,我发现:

  • napp.callback初始化为 …

javascript python callback collapse plotly-dash

2
推荐指数
1
解决办法
7404
查看次数