无法使用plotly在python中显示图

无法使用plotly在python中显示图

您好,我基本上是python的新手...我正在运行代码,以根据条形图找出单词和图解的频率。

以下是代码:

lyrics="Ah, Ba Ba Ba Ba Barbara Ann Ba Ba Ba Ba Barbara Ann Oh Barbara Ann Take My Hand Barbara Ann You Got Me Rockin' And A-Rollin' Rockin' And A-Reelin' Barbara Ann Ba Ba Ba Barbara Ann ...More Lyrics... Ba Ba Ba Ba Barbara Ann Ba Ba Ba Ba Barbara Ann"
list_of_lyrics = lyrics.split(' ')
len(list_of_lyrics)
unique_words = set(list_of_lyrics)
len(unique_words)
word_histogram = dict.fromkeys(unique_words, 0)
for word in list_of_lyrics:
    word_histogram[word] = word_histogram[word]+ 1

import plotly
from plotly.offline import iplot, init_notebook_mode
from plotly import tools
import plotly.graph_objs as go
init_notebook_mode(connected=True)

trace = {'type': 'bar', 'x': list(unique_words), 'y': list(word_histogram.values())}

plotly.offline.iplot({'data': [trace]})


输出为:

{'text/html': "<script>requirejs.config({paths: { 'plotly': ['https://cdn.plot.ly/plotly-latest.min']},});if(!window.Plotly) {{require(['plotly'],function(plotly) {window.Plotly=plotly;});}}</script>", 'text/vnd.plotly.v1+html': "<script>requirejs.config({paths: { 'plotly': }

最佳答案

适用于Python3的解决方案:

#import all the neccessaries packages
import plotly
import plotly.graph_objs as go
#Your code almost without changes
lyrics="Ah, Ba Ba Ba Ba Barbara Ann Ba Ba Ba Ba Barbara Ann Oh Barbara Ann " \
       "Take My Hand Barbara Ann You Got Me Rockin' And A-Rollin' Rockin' " \
       "And A-Reelin' Barbara Ann Ba Ba Ba Barbara Ann ...More Lyrics... " \
       "Ba Ba Ba Ba Barbara Ann Ba Ba Ba Ba Barbara Ann"
list_of_lyrics = lyrics.split(" ")
print(len(list_of_lyrics))
unique_words = set(list_of_lyrics)
print(len(unique_words))
word_histogram = dict.fromkeys(unique_words, 0)
for word in list_of_lyrics:
    word_histogram[word] = word_histogram[word]+ 1
print(word_histogram)
# Create trace (needed to do a plot)
trace = go.Bar(x = list(unique_words), y = list(word_histogram.values()))
# Set our trace in list which named data
data = [trace]
# Specify layout if you want to add a titles to your plot
layout = go.Layout(title = "Lyrics frequency",
                   xaxis = dict(title="Words from lyrics list"),
                   yaxis = dict(title="Frequency of each word in the list")
                   )
# Create fig, that contains all what we need to do a plot
fig = go.Figure(data=data, layout=layout)
# Call plotly in offline mode, choose name for plot and save him in directory
# where your Python script is
plotly.offline.plot(fig, filename="Lyrics frequency.html", auto_open=False)

关于python - 无法使用plotly在python中显示图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51936560/

10-12 20:07