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 draw dynamic Visual Chart with Python

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to draw dynamic visual charts with Python". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "How to draw dynamic visual charts with Python"!

installation module

If you don't already have Plotly installed, simply run the following command on your terminal:

pip install plotly visualizing dynamic diagrams

In studying the evolution of this or that metric, we often refer to time data. The Plotly animation tool allows you to see how your data changes over time with just one line of code, as shown below:

The code is as follows:

import plotly.express as pxfrom vega_datasets import datadf = data.disasters()df = df[df.Year > 1990]fig = px.bar(df, y="Entity", x="Deaths", animation_frame="Year", orientation='h', range_x=[0, df.Deaths.max()], color="Entity")# improve aesthetics (size, grids etc.) fig.update_layout(width=1000, height=800, xaxis_showgrid=False, yaxis_showgrid=False, paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', title_text='Evolution of Natural Disasters', showlegend=False)fig.update_xaxes(title_text='Number of Deaths')fig.update_yaxes(title_text='')fig.show()

As long as you have a time variable to filter through, almost any chart can be animated. Here is an example of how to animate a scatterplot:

import plotly.express as pxdf = px.data.gapminder()fig = px.scatter( df, x="gdpPercap", y="lifeExp", animation_frame="year", size="pop", color="continent", hover_name="country", log_x=True, size_max=55, range_x=[100, 100000], range_y=[25, 90], # color_continuous_scale=px.colors.sequential.Emrld)fig.update_layout(width=1000, height=800, xaxis_showgrid=False, yaxis_showgrid=False, paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)') solar plot

A sunburst chart is a good way to visualize group by statements. If you want to decompose a given quantity by one or more categorical variables, use a solar graph.

Assuming we want to break down the average tip data by gender and time of day, this double group by statement can be presented more effectively visually than a table.

This chart is interactive, allowing you to click and explore the categories yourself. All you have to do is define all your categories, declare the hierarchy between them (see the parents parameter in the code below), and assign the corresponding values, which in our case is the output of the group by statement.

import plotly.graph_objects as goimport plotly.express as pximport numpy as npimport pandas as pddf = px.data.tips()fig = go.Figure(go.Sunburst( labels=["Female", "Male", "Dinner", "Lunch", 'Dinner ', 'Lunch '], parents=["", "", "Female", "Female", 'Male', 'Male'], values=np.append( df.groupby('sex').tip.mean().values, df.groupby(['sex', 'time']).tip.mean().values), marker=dict(colors=px.colors.sequential.Emrld)), layout=go.Layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)'))fig.update_layout(margin=dict(t=0, l=0, r=0, b=0), title_text='Tipping Habbits Per Gender, Time and Day')fig.show()

Now we add another layer to this hierarchy:

To do this, we add the value of another group by statement involving three categorical variables.

import plotly.graph_objects as goimport plotly.express as pximport pandas as pdimport numpy as npdf = px.data.tips()fig = go.Figure(go.Sunburst(labels=[ "Female", "Male", "Dinner", "Lunch", 'Dinner ', 'Lunch ', 'Fri', 'Sat', 'Sun', 'Thu', 'Fri ', 'Thu ', 'Fri ', 'Sat ', 'Sun ', 'Fri ', 'Thu '], parents=[ "", "", "Female", "Female", 'Male', 'Male', 'Dinner', 'Dinner', 'Dinner', 'Dinner', 'Lunch', 'Lunch', 'Dinner ', 'Dinner ', 'Dinner ', 'Lunch ', 'Lunch ' ], values=np.append( np.append( df.groupby('sex').tip.mean().values, df.groupby(['sex', 'time']).tip.mean().values, ), df.groupby(['sex', 'time', 'day']).tip.mean().values), marker=dict(colors=px.colors.sequential.Emrld)), layout=go.Layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)'))fig.update_layout(margin=dict(t=0, l=0, r=0, b=0), title_text='Tipping Habbits Per Gender, Time and Day') fig.show() pointer diagram

The pointer diagram is just for the sake of looking good. Use this chart when reporting success metrics such as KPIs and showing how far they are from your goals.

import plotly.graph_objects as gofig = go.Figure(go.Indicator( domain = {'x': [0, 1], 'y': [0, 1]}, value = 4.3, mode = "gauge+number+delta", title = {'text': "Success Metric"}, delta = {'reference': 3.9}, gauge = {'bar': {'color': "lightgreen"}, 'axis': {'range': [None, 5]}, 'steps' : [ {'range': [0, 2.5], 'color': "lightgray"}, {'range': [2.5, 4], 'color': "gray"}], })fig.show() Sankey graph

Another way to explore the relationships between categorical variables is to use this parallel graph. You can drag and drop, highlight and browse values at any time, perfect for presentations.

The code is as follows:

import plotly.express as pxfrom vega_datasets import dataimport pandas as pddf = data.movies()df = df.dropna()df['Genre_id'] = df.Major_Genre.factorize()[0]fig = px.parallel_categories( df, dimensions=['MPAA_Rating', 'Creative_Type', 'Major_Genre'], color="Genre_id", color_continuous_scale=px.colors.sequential.Emrld,)fig.show() parallel coordinate graph

The parallel plot is a derivative version of the graph above. Here, each string represents a single observation. This is a useful tool for identifying outliers (single lines away from other data), clusters, trends, and redundant variables (e.g., if two variables have similar values on each observation, they will lie on the same horizontal line, indicating redundancy).

The code is as follows:

import plotly.express as pxfrom vega_datasets import dataimport pandas as pddf = data.movies()df = df.dropna()df['Genre_id'] = df.Major_Genre.factorize()[0]fig = px.parallel_coordinates( df, dimensions=[ 'IMDB_Rating', 'IMDB_Votes', 'Production_Budget', 'Running_Time_min', 'US_Gross', 'Worldwide_Gross', 'US_DVD_Sales' ], color='IMDB_Rating', color_continuous_scale=px.colors.sequential.Emrld) fig.show () At this point, I believe that everyone has a deeper understanding of "how to draw dynamic visual charts in Python," so let's actually operate it! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

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