簡體   English   中英

將 Matplotlib 的圖形傳遞給 Python 中的 Plotly Dash Graph

[英]Passing Matplotlib's figure to a Plotly Dash Graph in Python

我正在使用 Matplotlib 在 python 中繪制一個句子的詞雲,如下所示:

import matplotlib.pyplot as plt 
from wordcloud import WordCloud, STOPWORDS
word_cloud = WordCloud(collocations = False, background_color = 'white').generate("This is a test sentence with the purpose of plotting a word cloud and converting it to dash graph object")
plt.axis('off')
image = plt.imshow(word_cloud, interpolation='bilinear')

結果如下所示:

在此處輸入圖像描述

我想將此圖像作為圖形對象傳遞給破折號的圖形。 我寫了以下代碼:

import dash
from dash.dependencies import Input, Output, State
from dash import dcc
from dash import dash_table, html
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import plotly.tools

app = dash.Dash(__name__)

app.layout = html.Div(children=[
html.A("Start",style={'backgroundColor':'green'},id='start'),
dcc.Graph(id='result')
])

@app.callback(
    Output('result', 'figure'),
    [Input('start', 'n_clicks')]
)
def update_figure(n1):
    word_cloud = WordCloud(collocations = False, background_color = 'white').generate("his is a test sentence with the purpose of plotting a word cloud and converting it to dash graph object")
    plt.axis('off')
    word_cloud_figure = plt.figure(word_cloud, interpolation='bilinear')
    if(n1):
        plotly.tools.mpl_to_plotly(word_cloud_figure)
    return word_cloud_figure

if __name__ == '__main__':
    app.run_server(debug=True, port=9872)

但我得到了這個錯誤:

TypeError: int() 參數必須是字符串、類似字節的對象或數字,而不是“WordCloud”

如何解決此問題並在破折號的圖表中顯示詞雲?

我找到了一種方法來使用下面的代碼來解決這個問題。 此外,我通過添加一個 ID 為“max-word-count”的 inout 字段來限制字數,以便在字數過多時使圖形看起來更好。

@app.callback(
    Output('indicator-graphic-for-word-clouds', 'figure'),
    [
        Input('description-dropdown', 'value'),
        Input('max-word-count', 'value')
    ], 
        State('analyzed-dataset', 'data')
    )
def update_graph(selected_description, max_word_count, analyzed_dataset):
    dataset = pd.DataFrame.from_dict(analyzed_dataset)
    text = ""
    if(selected_description == "All"):
        temp_dataset = dataset['description']
        for review in temp_dataset:
            text += review
    else:
         temp_dataset = dataset[dataset['comment'] == selected_description]['description']
        print(temp_dataset)
        for review in temp_dataset:
            text += review
            text += "\n"
    tokenizer = nltk.RegexpTokenizer(r"\w+")
    tokenized_review = tokenizer.tokenize(text.lower())
    filtered_review = [word for word in tokenized_review if word not in stopwords.words('english')]
    word_count = 0
    try:
        word_count = int(max_word_count)
        if(word_count > len(filtered_review)):
            word_count = len(filtered_review)
    except:
        word_count = len(filtered_review)
    colors = [plotly.colors.DEFAULT_PLOTLY_COLORS[random.randrange(1, 10)] for i in range(word_count)]
    weights = [random.randint(15, 35) for i in range(word_count)]
    data = go.Scatter(x=[random.random() for i in range(word_count)],
        y=[random.random() for i in range(word_count)],
        mode='text',
        text=filtered_review,
        marker={'opacity': 0.3},
        textfont={'size': weights,
                'color': colors})
    layout = go.Layout({'xaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False},
    'yaxis': {'showgrid': False, 'showticklabels': False, 'zeroline': False}})
    fig = go.Figure(data=[data], layout=layout)
    return fig

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM