


Python draws stunning Sankey diagrams, have you learned it?
Apr 12, 2023 pm 02:28 PMIntroduction to Sankey Diagram
Many times, we need a situation where we must visualize how data flows between entities. For example, take how residents move from one country to another. Here's a demonstration of how many residents moved from England to Northern Ireland, Scotland and Wales.
It is clear from this Sankey visualization that more residents moved from England to Wales than from Scotland or Northern Ireland.
What is a Sankey diagram?
Sankey diagrams usually depict the flow of data from one entity (or node) to another entity (or node).
The entities to which data flows are called nodes. The node where the data flow originates is the source node (for example, England on the left), and the node where the flow ends is the target node (for example, Wales on the right). Source and target nodes are usually represented as labeled rectangles.
The flow itself is represented by straight or curved paths, called links. The width of a stream/link is directly proportional to the volume/number of streams. In the example above, the movement from England to Wales (i.e. the migration of residents) is more extensive (i.e. the migration of residents) than the movement from England to Scotland or Northern Ireland (i.e. the migration of residents), indicating that more residents move to Wales than to other countries .
Sankey diagrams can be used to represent the flow of energy, money, costs, and anything that has a flow concept.
Minard's classic chart of Napoleon's invasion of Russia is probably the most famous example of a Sankey chart. This visualization using a Sankey diagram shows very effectively how the French army progressed (or decreased?) on its way to Russia and back.
#In this article, we use python’s plotly to draw a Sankey diagram.
How to draw a Sankey diagram?
This article uses the 2021 Olympic Games data set to draw a Sankey diagram. The dataset contains detailed information about the total number of medals - country, total number of medals, and individual totals for gold, silver, and bronze medals. We plot a Sankey chart to find out how many gold, silver and bronze medals a country has won.
df_medals = pd.read_excel("data/Medals.xlsx") print(df_medals.info()) df_medals.rename(columns={'Team/NOC':'Country', 'Total': 'Total Medals', 'Gold':'Gold Medals', 'Silver': 'Silver Medals', 'Bronze': 'Bronze Medals'}, inplace=True) df_medals.drop(columns=['Unnamed: 7','Unnamed: 8','Rank by Total'], inplace=True) df_medals
<class 'pandas.core.frame.DataFrame'> RangeIndex: 93 entries, 0 to 92 Data columns (total 9 columns): # Column Non-Null CountDtype --------- ------------------- 0 Rank 93 non-null int64 1 Team/NOC 93 non-null object 2 Gold 93 non-null int64 3 Silver 93 non-null int64 4 Bronze 93 non-null int64 5 Total93 non-null int64 6 Rank by Total93 non-null int64 7 Unnamed: 7 0 non-nullfloat64 8 Unnamed: 8 1 non-nullfloat64 dtypes: float64(2), int64(6), object(1) memory usage: 6.7+ KB None
Sankey diagram drawing basics
Use plotly's go.Sankey, this method takes 2 parameters - nodes and links (nodes and links ).
Note: All nodes - source and target should have unique identifiers.
In the case of the Olympic medals data set in this article:
Source is the country. Consider the first 3 countries (United States, China, and Japan) as source nodes. Label these source nodes with the following (unique) identifiers, labels, and colors:
- 0: United States: Green
- 1: China: Blue
- 2: Japan: Orange
Target is gold, silver or bronze. Label these target nodes with the following (unique) identifiers, labels, and colors:
- 3: Gold Medal: Gold
- 4: Silver Medal: Silver
- 5 : Bronze: Brown
Link (between source node and target node) is the number of medals of each type. In each source there are 3 links, each ending with a target - Gold, Silver and Bronze. So there are 9 links in total. The width of each link should be the number of gold, silver and bronze medals. Tag these links to targets, values ??and colors with the following sources:
- 0 (US) to 3,4,5 : 39, 41, 33
- 1 (China) to 3 ,4,5 : 38, 32, 18
- 2 (Japan) to 3,4,5 : 27, 14, 17
You need to instantiate 2 python dict objects to Represents
- nodes (source and target): labels and colors as separate lists and
- links: source node, target node, value (width) and color of the link as separate List
and pass it to plotly's go.Sankey.
Each index of the list (label, source, target, value and color) corresponds to a node or link.
NODES = dict( # 0 1 23 4 5 label = ["United States of America", "People's Republic of China", "Japan", "Gold", "Silver", "Bronze"], color = ["seagreen", "dodgerblue", "orange", "gold", "silver", "brown" ],) LINKS = dict( source = [0,0,0,1,1,1,2,2,2], # 鏈接的起點(diǎn)或源節(jié)點(diǎn) target = [3,4,5,3,4,5,3,4,5], # 鏈接的目的地或目標(biāo)節(jié)點(diǎn) value =[ 39, 41, 33, 38, 32, 18, 27, 14, 17], # 鏈接的寬度(數(shù)量) # 鏈接的顏色 # 目標(biāo)節(jié)點(diǎn): 3-Gold4-Silver5-Bronze color = [ "lightgreen", "lightgreen", "lightgreen",# 源節(jié)點(diǎn):0 - 美國(guó) States of America "lightskyblue", "lightskyblue", "lightskyblue",# 源節(jié)點(diǎn):1 - 中華人民共和國(guó)China "bisque", "bisque", "bisque"],)# 源節(jié)點(diǎn):2 - 日本 data = go.Sankey(node = NODES, link = LINKS) fig = go.Figure(data) fig.show()
This is a very basic Sankey diagram. But have you noticed that the chart is too wide and the silver medals appear before the gold medals?
Here’s how to adjust the position and width of nodes.
Adjust node positions and chart width
Add x and y positions to nodes to explicitly specify the node's position. Value should be between 0 and 1.
NODES = dict( # 0 1 23 4 5 label = ["United States of America", "People's Republic of China", "Japan", "Gold", "Silver", "Bronze"], color = ["seagreen", "dodgerblue", "orange", "gold", "silver", "brown" ],) x = [ 0,0,0,0.5,0.5,0.5], y = [ 0,0.5,1,0.1,0.5,1],) data = go.Sankey(node = NODES, link = LINKS) fig = go.Figure(data) fig.update_layout(title="Olympics - 2021: Country &Medals",font_size=16) fig.show()
So we got a compact Sankey diagram:
Let’s take a look at how the various parameters passed in the code are mapped to the nodes and nodes in the graph. Link.
代碼如何映射到?;鶊D
添加有意義的懸停標(biāo)簽
我們都知道plotly繪圖是交互的,我們可以將鼠標(biāo)懸停在節(jié)點(diǎn)和鏈接上以獲取更多信息。
帶有默認(rèn)懸停標(biāo)簽的?;鶊D
當(dāng)將鼠標(biāo)懸停在圖上,將會(huì)顯示詳細(xì)信息。懸停標(biāo)簽中顯示的信息是默認(rèn)文本:節(jié)點(diǎn)、節(jié)點(diǎn)名稱、傳入流數(shù)、傳出流數(shù)和總值。
例如:
- 節(jié)點(diǎn)美國(guó)共獲得11枚獎(jiǎng)牌(=39金+41銀+33銅)
- 節(jié)點(diǎn)金牌共有104枚獎(jiǎng)牌(=美國(guó)39枚,中國(guó)38枚,日本27枚)
如果我們覺(jué)得這些標(biāo)簽太冗長(zhǎng)了,我們可以對(duì)此進(jìn)程改進(jìn)。使用hovertemplate參數(shù)改進(jìn)懸停標(biāo)簽的格式
- 對(duì)于節(jié)點(diǎn),由于hoverlabels 沒(méi)有提供新信息,通過(guò)傳遞一個(gè)空hovertemplate = ""來(lái)去掉hoverlabel
- 對(duì)于鏈接,可以使標(biāo)簽簡(jiǎn)潔,格式為-
- 對(duì)于節(jié)點(diǎn)和鏈接,讓我們使用后綴"Medals"顯示值。例如 113 枚獎(jiǎng)牌而不是 113 枚。這可以通過(guò)使用具有適當(dāng)valueformat和valuesuffix的update_traces函數(shù)來(lái)實(shí)現(xiàn)。
NODES = dict( # 0 1 23 4 5 label = ["United States of America", "People's Republic of China", "Japan", "Gold", "Silver", "Bronze"], color = ["seagreen", "dodgerblue","orange", "gold", "silver", "brown" ], x = [ 0,0, 0,0.5,0.5,0.5], y = [ 0,0.5, 1,0.1,0.5,1], hovertemplate=" ",) LINK_LABELS = [] for country in ["USA","China","Japan"]: for medal in ["Gold","Silver","Bronze"]: LINK_LABELS.append(f"{country}-{medal}") LINKS = dict(source = [0,0,0,1,1,1,2,2,2], # 鏈接的起點(diǎn)或源節(jié)點(diǎn) target = [3,4,5,3,4,5,3,4,5], # 鏈接的目的地或目標(biāo)節(jié)點(diǎn) value =[ 39, 41, 33, 38, 32, 18, 27, 14, 17], # 鏈接的寬度(數(shù)量) # 鏈接的顏色 # 目標(biāo)節(jié)點(diǎn):3-Gold4 -Silver5-Bronze color = ["lightgreen", "lightgreen", "lightgreen", # 源節(jié)點(diǎn):0 - 美國(guó) "lightskyblue", "lightskyblue", "lightskyblue", # 源節(jié)點(diǎn):1 - 中國(guó) "bisque", "bisque", "bisque"],# 源節(jié)點(diǎn):2 - 日本 label = LINK_LABELS, hovertemplate="%{label}",) data = go.Sankey(node = NODES, link = LINKS) fig = go.Figure(data) fig.update_layout(title="Olympics - 2021: Country &Medals", font_size=16, width=1200, height=500,) fig.update_traces(valueformat='3d', valuesuffix='Medals', selector=dict(type='sankey')) fig.update_layout(hoverlabel=dict(bgcolor="lightgray", font_size=16, font_family="Rockwell")) fig.show("png") #fig.show()
帶有改進(jìn)的懸停標(biāo)簽的?;鶊D
對(duì)多個(gè)節(jié)點(diǎn)和級(jí)別進(jìn)行泛化相對(duì)于鏈接,節(jié)點(diǎn)被稱為源和目標(biāo)。作為一個(gè)鏈接目標(biāo)的節(jié)點(diǎn)可以是另一個(gè)鏈接的源。
該代碼可以推廣到處理數(shù)據(jù)集中的所有國(guó)家。
還可以將圖表擴(kuò)展到另一個(gè)層次,以可視化各國(guó)的獎(jiǎng)牌總數(shù)。
NUM_COUNTRIES = 5 X_POS, Y_POS = 0.5, 1/(NUM_COUNTRIES-1) NODE_COLORS = ["seagreen", "dodgerblue", "orange", "palevioletred", "darkcyan"] LINK_COLORS = ["lightgreen", "lightskyblue", "bisque", "pink", "lightcyan"] source = [] node_x_pos, node_y_pos = [], [] node_labels, node_colors = [], NODE_COLORS[0:NUM_COUNTRIES] link_labels, link_colors, link_values = [], [], [] # 第一組鏈接和節(jié)點(diǎn) for i in range(NUM_COUNTRIES): source.extend([i]*3) node_x_pos.append(0.01) node_y_pos.append(round(i*Y_POS+0.01,2)) country = df_medals['Country'][i] node_labels.append(country) for medal in ["Gold", "Silver", "Bronze"]: link_labels.append(f"{country}-{medal}") link_values.append(df_medals[f"{medal} Medals"][i]) link_colors.extend([LINK_COLORS[i]]*3) source_last = max(source)+1 target = [ source_last, source_last+1, source_last+2] * NUM_COUNTRIES target_last = max(target)+1 node_labels.extend(["Gold", "Silver", "Bronze"]) node_colors.extend(["gold", "silver", "brown"]) node_x_pos.extend([X_POS, X_POS, X_POS]) node_y_pos.extend([0.01, 0.5, 1]) # 最后一組鏈接和節(jié)點(diǎn) source.extend([ source_last, source_last+1, source_last+2]) target.extend([target_last]*3) node_labels.extend(["Total Medals"]) node_colors.extend(["grey"]) node_x_pos.extend([X_POS+0.25]) node_y_pos.extend([0.5]) for medal in ["Gold","Silver","Bronze"]: link_labels.append(f"{medal}") link_values.append(df_medals[f"{medal} Medals"][:i+1].sum()) link_colors.extend(["gold", "silver", "brown"]) print("node_labels", node_labels) print("node_x_pos", node_x_pos); print("node_y_pos", node_y_pos)
node_labels ['United States of America', "People's Republic of China", 'Japan', 'Great Britain', 'ROC', 'Gold', 'Silver', 'Bronze', 'Total Medals'] node_x_pos [0.01, 0.01, 0.01, 0.01, 0.01, 0.5, 0.5, 0.5, 0.75] node_y_pos [0.01, 0.26, 0.51, 0.76, 1.01, 0.01, 0.5, 1, 0.5]
# 顯示的圖 NODES = dict(pad= 20, thickness = 20, line = dict(color = "lightslategrey", width = 0.5), hovertemplate=" ", label = node_labels, color = node_colors, x = node_x_pos, y = node_y_pos, ) LINKS = dict(source = source, target = target, value = link_values, label = link_labels, color = link_colors, hovertemplate="%{label}",) data = go.Sankey(arrangement='snap', node = NODES, link = LINKS) fig = go.Figure(data) fig.update_traces(valueformat='3d', valuesuffix=' Medals', selector=dict(type='sankey')) fig.update_layout(title="Olympics - 2021: Country &Medals", font_size=16, width=1200, height=500,) fig.update_layout(hoverlabel=dict(bgcolor="grey", font_size=14, font_family="Rockwell")) fig.show("png")
The above is the detailed content of Python draws stunning Sankey diagrams, have you learned it?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

When choosing a suitable PHP framework, you need to consider comprehensively according to project needs: Laravel is suitable for rapid development and provides EloquentORM and Blade template engines, which are convenient for database operation and dynamic form rendering; Symfony is more flexible and suitable for complex systems; CodeIgniter is lightweight and suitable for simple applications with high performance requirements. 2. To ensure the accuracy of AI models, we need to start with high-quality data training, reasonable selection of evaluation indicators (such as accuracy, recall, F1 value), regular performance evaluation and model tuning, and ensure code quality through unit testing and integration testing, while continuously monitoring the input data to prevent data drift. 3. Many measures are required to protect user privacy: encrypt and store sensitive data (such as AES

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"

The core idea of PHP combining AI for video content analysis is to let PHP serve as the backend "glue", first upload video to cloud storage, and then call AI services (such as Google CloudVideoAI, etc.) for asynchronous analysis; 2. PHP parses the JSON results, extract people, objects, scenes, voice and other information to generate intelligent tags and store them in the database; 3. The advantage is to use PHP's mature web ecosystem to quickly integrate AI capabilities, which is suitable for projects with existing PHP systems to efficiently implement; 4. Common challenges include large file processing (directly transmitted to cloud storage with pre-signed URLs), asynchronous tasks (introducing message queues), cost control (on-demand analysis, budget monitoring) and result optimization (label standardization); 5. Smart tags significantly improve visual

To integrate AI sentiment computing technology into PHP applications, the core is to use cloud services AIAPI (such as Google, AWS, and Azure) for sentiment analysis, send text through HTTP requests and parse returned JSON results, and store emotional data into the database, thereby realizing automated processing and data insights of user feedback. The specific steps include: 1. Select a suitable AI sentiment analysis API, considering accuracy, cost, language support and integration complexity; 2. Use Guzzle or curl to send requests, store sentiment scores, labels, and intensity information; 3. Build a visual dashboard to support priority sorting, trend analysis, product iteration direction and user segmentation; 4. Respond to technical challenges, such as API call restrictions and numbers

The core of PHP's development of AI text summary is to call external AI service APIs (such as OpenAI, HuggingFace) as a coordinator to realize text preprocessing, API requests, response analysis and result display; 2. The limitation is that the computing performance is weak and the AI ecosystem is weak. The response strategy is to leverage APIs, service decoupling and asynchronous processing; 3. Model selection needs to weigh summary quality, cost, delay, concurrency, data privacy, and abstract models such as GPT or BART/T5 are recommended; 4. Performance optimization includes cache, asynchronous queues, batch processing and nearby area selection. Error processing needs to cover current limit retry, network timeout, key security, input verification and logging to ensure the stable and efficient operation of the system.

String lists can be merged with join() method, such as ''.join(words) to get "HelloworldfromPython"; 2. Number lists must be converted to strings with map(str, numbers) or [str(x)forxinnumbers] before joining; 3. Any type list can be directly converted to strings with brackets and quotes, suitable for debugging; 4. Custom formats can be implemented by generator expressions combined with join(), such as '|'.join(f"[{item}]"foriteminitems) output"[a]|[
