简体   繁体   中英

not able to display plots in python with plotly

Hello I am basically new to python... I am running the code to find out no of frequencies of the words and plots in the basis of bar plot.

Follow is the code:

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]})

output is:

{'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': }

Worked solution for 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM