Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python Visualization tool Plotly

2025-04-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how to use the Python visualization tool Plotly, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

one。 Brief introduction

The origin of the development:

With the development of information technology and the reduction of the cost of hardware equipment, there are huge amounts of data on the Internet today. If you want to quickly get more effective information from these data, data visualization is an important part. For Python language, the more traditional data visualization module is Matplotlib, but it has some shortcomings, such as not beautiful, static, difficult to share and so on, which limits the development of Python in data visualization.

In order to solve this problem, a new dynamic visualization open source module Plotly arises at the historic moment. Because Plotly is dynamic, beautiful, easy to use, rich in variety and so on, it has been loved by developers as soon as it came out.

Brief description

Plotly is an interactive, open source drawing library in the Python library, and it is also a javascript-based drawing library that supports more than 40 unique chart types with beautiful results, covering a variety of statistical, financial, geographic, scientific and 3D use cases.

Online and offline modes, easy to save and share plotly drawing results, and seamless integration with Web

The default drawing result of ploty is a HTML web page file, which can be viewed directly through the browser.

two。 The application of each map

Installation:

Pip install plotly

The following are all run in Jupyter Notebook

Data source:

Import plotlyimport plotly.express as pximport plotly.graph_objects as goimport plotly.io as pioimport pandas as pdimport numpy as np# plotly has a built-in data set, which makes it convenient for you to practice using df=px.data.gapminder () df.head () without the idea of data analysis.

Running result:

1. Bar chart # draw the population change chart of China over the years # df_country=df.query ('country== "China') df_country=df [df ['country'] = =' China'] # column chart shows fig=px.bar (df_country, # data source x years old yearbook, # Abscissa: year yearly poppy, # ordinate: population text='pop' # description: population color='lifeExp', # color value: take hover_name='year', # control point name: year) fig according to the average life span

Running result:

# Note title fig.update_layout (title_text=' history of population changes in China', title_x=.5, font=dict (family='simsun', size=14, color='#1d39c4')) # Note axis fig.update_layout (xaxis_title=' year' Yaxis_title=' population') fig

Running result:

# column chart text format fig.update_traces (textposition='outside', texttemplate='% {text:,.2s}') fig

Running result:

# using customdata to add dataset fig.update_traces (customdata=df [['lifeExp','gdpPercap']]) fig.update_traces (hovertemplate='Year:% {x})

Population:% {y}

Life Expectation:% {customdata [0]:, .2f}

GDP per capital:% {customdata [1]:, .2f}') # Axis tick sets fig.update_xaxes (tickangle=-45,tickfont=dict (family='arial',size=12)) fig

Running result:

# set gap size and text size fig.update_layout (bargap=.4, uniformtext_minsize=8, uniformtext_mode='show') # set annotations fig.add_annotation (xtended 1982, yaq1000281000, text=' break 1 billion', font=dict (color='red')) fig.update_annotations (dict (xref='x') Yref='y', showarrow=True), arrowcolor='red', arrowhead=4) fig.show ()

Running result:

two。 Scatter plot df_2007 = df [df ["year"] = = 2007] df_2007

Running result:

# scatter plot px.scatter (df_2007, # dataset x = "gdpPercap", # Abscissa: per capita GDP y = "lifeExp", # ordinate: average life color= "continent" # Color value: based on continent value)

Running result:

Select an area that can be magnified

3. Bubble scatter chart # bubble scatter chart px.scatter (df_2007, # drawing DataFrame dataset x = "gdpPercap", # Abscissa y = "lifeExp", # ordinate color= "continent", # distinguishing color size= "pop", # distinguishing circle size size_max=60 # scatter size hover_name= "country" # Control Point name)

Running result:

4. Px.sunburst (df_2007, # drawing data path= ['continent',' country'], # specified path: from continent to country values='pop', # data size: population color='lifeExp', # Color hover_data= ['iso_alpha'] # display data)

Running result:

5. Map graphics # set map graphics px.choropleth (df, # data locations= "iso_alpha", # referred to as color= "lifeExp", # color values hover_name= "country", # hover data animation_frame= "year", # playback button settings color_continuous_scale=px.colors.sequential.Plasma, # color change values projection= "natural earth" # Map settings used)

Running result:

three。 Actual combat case

Using the Titanic to survive as an example

Import plotlyimport plotly.express as pximport plotly.graph_objects as goimport plotly.io as pioimport pandas as pdimport numpy as np# data read path2='./dataSet/test.csv'path3='./dataSet/train.csv'test=pd.read_csv (path2) train=pd.read_csv (path3) # data merge data=pd.concat ([test,train])

Running result:

# display the survived distribution in the data df1=pd.DataFrame (data=data ['Survived']. Value_counts ()) df1

Running result:

Fig1=px.bar (df1,y='Survived',text='Survived',color_discrete_sequence= [['# B4C7ECM]]) fig1.update_layout (title='Survival Status in Titanic', title_x=.5, xaxis_title='Passenger survival status', yaxis_title='Numbers', font=dict (family='arial',color='#000000',size=12)) Bargap=.5) fig1.update_xaxes (tick0=0, # set the start point of the X axis Prevent dtick=1 from starting with negative numbers, # set intervals, prevent 0.5 intervals tickvals= [0pencil 1], # set tick values To rename ticktext= ['Drowned','Suvived'], # rename series index tickfont=dict (family='arial',color='#000000',size=14) fig1.update_yaxes (range= [0650]) # set the Y-axis interval so that graphics do not visually oppress fig1.update_traces (textposition='outside', textfont_size=16, textfont_color= [' # 8C1004') '# 007046']) fig1.show ()

Running result:

# take survived and sex as examples to show the relative relationship between survival and death in different genders. Df_sex=pd.DataFrame (data=data.groupby (['Survived','Sex']) [' PassengerId'] .count ()) df_sex=df_sex.reset_index () df_sex

Running result:

Fig_sex1=px.bar (df_sex,x='Survived',y='PassengerId',color='Sex',barmode='group',text='PassengerId', color_discrete_map= {'female':'#F17F0B','male':'#0072E5'}) fig_sex1.update_traces (textposition='outside', textfont_size=14, textfont_color= [' # 8C1004'' '# 007046']) fig_sex1.update_xaxes (tickvals= [0Pol 1], # set the tick value To rename ticktext= ['Drowned','Suvived'], # rename series index tickfont=dict (family='arial', color='#000000', size=14) fig_sex1.update_layout (title='Overall Suvival in terms of Sex', title_x=.5, bargap=.35) Xaxis_title='', yaxis_title='Numbers of Passengers', font=dict (family='arial', color='#000000', size=13)) fig_sex1.update_yaxes (range= [0500], dtick=100) fig_sex1.show ()

Running result:

Fig_sex2=px.bar (df_sex,x='Sex',y='PassengerId',facet_col='Survived',text='PassengerId', color_discrete_sequence= [['# F17F0B]]) fig_sex2.update_traces (textposition='outside', textfont_size=14,) fig_sex2.update_layout (title='Overall Suvival in terms of Sex', title_x=.5) Bargap=.35, yaxis_title='Numbers of Passengers', font=dict (family='arial', color='#000000', size=13),) # cancel the sex title fig_sex2.update_layout (xaxis=dict (title='')) Xaxis2=dict (title='')) fig_sex2.update_yaxes (range= [0500], dtick=100) fig_sex2.for_each_annotation (lambda a:a.update (text=a.text.replace ('Survived=0.0','Drowned') fig_sex2.for_each_annotation (lambda a:a.update (text=a.text.replace (' Survived=1.0','Suvived') fig_sex2.update_layout (annotations= [dict (font=dict (size=16)) Color='#002CB2')]) fig_sex2.show ()

Running result:

# take survived and pclass as examples to show the relative relationship between survival and death under each class of space. Df_pclass=pd.DataFrame (data=data.groupby (['Survived','Pclass']) [' PassengerId'] .count ()) df_pclass=df_pclass.reset_index () df_pclass

Running result:

Fig_sex1=px.bar (textposition='outside', textfont_size=14, textfont_color= ['# 8C1004'') fig_sex1=px.bar (textposition='outside', textfont_size=14, textfont_color= ['# 8C1004'') '# 007046']) fig_sex1.update_xaxes (tickvals= [0Pol 1], # set the tick value To rename ticktext= ['Drowned','Suvived'], # rename series index tickfont=dict (family='arial', color='#000000', size=14) fig_sex1.update_layout (title='Overall Suvival in terms of Pclass', title_x=.5, bargap=.35) Xaxis_title='', yaxis_title='Numbers of Passengers', font=dict (family='arial', color='#000000', size=13)) fig_sex1.update_yaxes (range= [0500], dtick=100) fig_sex1.show ()

Running result:

The above is all the contents of this article entitled "how to use Python Visualization tool Plotly". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report