Pie and Gauge Charts: Unlocking Interactivity with Plotly.js, Part 5
Aug 31, 2023 pm 08:53 PMIf you've been following this series since the beginning, you may have noticed that Plotly.js uses the same scatter
type to create line and bubble charts. The only difference is that we have to set mode
to lines
when creating a line chart and markers
to when creating a bubble chart mode
.
Similarly, Plotly.js allows you to create pie charts, donut charts, and gauge charts by using the same value for the type
property and changing the values ??of other properties depending on the chart you want to create.
Creating pie charts in Plotly.js
You can create a pie chart in Plotly.js by setting the type
property to pie
. There are other properties such as opacity
, visible
, and name
that are also common to other chart types. The name
attribute is used to provide the name of the current pie trace. This name is then shown in the legend for identification. You can show or hide the pie chart trace in the chart legend by setting the showlegend
property to true
or false
respectively. You can use the labels
attribute to set label names for different parts of the pie chart.
For pie charts, marker objects are used to control the appearance of different parts of the chart. The color
property nested within marker
can be used to set the color of each slice of the pie chart. The colors of different sectors can be specified as array values ??of the color
property.
You can also set the color and width of all lines surrounding each sector using the color
and width
properties nested within the line object. You also have the option of sorting all slices of the pie chart from largest to smallest using the boolean sort
property. Likewise, with the help of the direction
property, you can change the direction of a sector to clockwise
or counterclockwise
.
The following code creates a basic pie chart that lists the forest area of ??the top five countries in the world.
var pieDiv = document.getElementById("pie-chart"); var traceA = { type: "pie", values: [8149300, 4916438, 4776980, 3100950, 2083210], labels: ['Russia', 'Canada', 'Brazil', 'United States', 'China'] }; var data = [traceA]; var layout = { title: "Area Under Forest for Different Countries" }; Plotly.plot(pieDiv, data, layout);
As you can see, we no longer use the x
and y
properties to specify the points we want to plot. Now, this is done with the help of values
and labels
. The percentage is automatically determined based on the entered value.
By default, the first slice of the pie chart starts at 12 o'clock. You can change the starting angle of the chart using the rotation
property, which accepts values ??between -360 and 360. The default 12 o'clock value is equal to angle 0.
If you want a certain slice in the chart to stand out, you can use the pull
property, which accepts a number or an array of numbers with values ??between 0 and 1. pull
Property is used to pull the specified sector from the pie chart. The pull distance is equal to a fraction of the larger radius of the pie or donut.
It is very easy to convert a pie chart into a donut chart by specifying the value of the hole
attribute. It will cut out a given radius portion from the pie chart to make a donut chart.
You can control the colors of individual sectors in the pie chart using the colors
property nested within the marker object. You can also change the width and color of the line surrounding each sector with the help of the width
and color
properties nested within the line object. The default width of the bounding line is 0. This means that by default no lines are drawn around the sectors.
There is also a hovertext
attribute that can be used to provide some additional text information for each individual sector. This information will be visible to viewers when they hover over a sector. One of the conditions for displaying text is that the hoverinfo
attribute should contain the text flag. You can set the text color inside or outside the pie chart sectors using the family
, size
, and color
properties nested in insidetextfont
and outsidetextfont
are objects respectively.
The following code uses the data from the previous pie chart to create a donut chart that uses the other properties we just learned about.
var pieDiv = document.getElementById("pie-chart"); var traceA = { type: "pie", values: [8149300, 4916438, 4776980, 3100950, 2083210], labels: ['Russia', 'Canada', 'Brazil', 'United States', 'China'], hole: 0.25, pull: [0.1, 0, 0, 0, 0], direction: 'clockwise', marker: { colors: ['#CDDC39', '#673AB7', '#F44336', '#00BCD4', '#607D8B'], line: { color: 'black', width: 3 } }, textfont: { family: 'Lato', color: 'white', size: 18 }, hoverlabel: { bgcolor: 'black', bordercolor: 'black', font: { family: 'Lato', color: 'white', size: 18 } } }; var data = [traceA]; var layout = { title: "Area Under Forest for Different Countries" }; Plotly.plot(pieDiv, data, layout);
在 Plotly.js 中創(chuàng)建儀表圖表
儀表圖的基本結(jié)構(gòu)與圓環(huán)圖類似。這意味著我們可以使用一些巧妙選擇的值并通過仍然將 type
屬性設(shè)置為 pie
來創(chuàng)建簡單的儀表圖表?;旧希覀儗㈦[藏整個餅圖的某些部分,使其看起來像儀表圖。
首先,我們需要為 values
屬性選擇一些值。為了簡單起見,我將使用餅圖的上半部分作為我的儀表圖。這意味著這些值應(yīng)該在我想要可見的部分和我想要隱藏的餅圖部分之間平均分配。圖表的可見部分可以進(jìn)一步分為更小的部分。以下是為儀表圖表選擇值的示例。
values: [100 / 5, 100 / 5, 100 / 5, 100 / 5, 100 / 5, 100]
上行中的數(shù)字 100 是任意的。可以看到,前五個切片加起來是100,這也是為餅圖隱藏區(qū)域設(shè)置的值。這將整個餡餅平均分為隱藏部分和可見部分。
這是創(chuàng)建基本儀表圖表的完整代碼。您應(yīng)該注意到,我已將應(yīng)隱藏的扇區(qū)的顏色屬性設(shè)置為白色。同樣,相應(yīng)扇區(qū)的 text
和 labels
值也已設(shè)置為空字符串。 rotation
屬性已設(shè)置為 90,以便圖表不會從默認(rèn)的 12 點(diǎn)鐘位置繪制。
var gaugeDiv = document.getElementById("gauge-chart"); var traceA = { type: "pie", showlegend: false, hole: 0.4, rotation: 90, values: [100 / 5, 100 / 5, 100 / 5, 100 / 5, 100 / 5, 100], text: ["Very Low", "Low", "Average", "Good", "Excellent", ""], direction: "clockwise", textinfo: "text", textposition: "inside", marker: { colors: ["rgba(255, 0, 0, 0.6)", "rgba(255, 165, 0, 0.6)", "rgba(255, 255, 0, 0.6)", "rgba(144, 238, 144, 0.6)", "rgba(154, 205, 50, 0.6)", "white"] }, labels: ["0-10", "10-50", "50-200", "200-500", "500-2000", ""], hoverinfo: "label" };
代碼的下一部分涉及儀表圖表的指針。您為 Degrees
變量設(shè)置的值將確定繪制針的角度。 radius
變量決定針的長度。屬性 x0
和 y0
用于設(shè)置線條的起點(diǎn)。同樣,屬性 x1
和 y1
用于設(shè)置線條的終點(diǎn)。
您可以借助 SVG 路徑為針創(chuàng)建更復(fù)雜的形狀。您所要做的就是將 type
屬性設(shè)置為 path
并使用 path
屬性指定實(shí)際路徑。您可以在參考的布局形狀部分閱讀更多相關(guān)信息。
var degrees = 115, radius = .6; var radians = degrees * Math.PI / 180; var x = -1 * radius * Math.cos(radians); var y = radius * Math.sin(radians); var layout = { shapes:[{ type: 'line', x0: 0, y0: 0, x1: x, y1: 0.5, line: { color: 'black', width: 8 } }], title: 'Number of Printers Sold in a Week', xaxis: {visible: false, range: [-1, 1]}, yaxis: {visible: false, range: [-1, 1]} }; var data = [traceA]; Plotly.plot(gaugeDiv, data, layout, {staticPlot: true});
本節(jié)的所有代碼都會創(chuàng)建以下儀表圖表。目前,該圖表不是很奇特,但它可以作為一個很好的起點(diǎn)。
最終想法
在本教程中,您學(xué)習(xí)了如何使用 Plotly.js 中的 pie
跟蹤類型創(chuàng)建餅圖和圓環(huán)圖。您還學(xué)習(xí)了如何仔細(xì)設(shè)置一些屬性的值,以將這些餅圖轉(zhuǎn)換為簡單的儀表圖。您可以在參考頁面上閱讀有關(guān)餅圖及其不同屬性的更多信息。
這是我們的交互式 Plotly.js 圖表系列的最后一個教程。第一個介紹性教程為您提供了該庫的概述。第二、第三和第四教程分別向您展示了如何創(chuàng)建折線圖、條形圖和氣泡圖。我希望您喜歡本教程以及整個系列。如果您有任何疑問,請隨時在評論中告訴我。
The above is the detailed content of Pie and Gauge Charts: Unlocking Interactivity with Plotly.js, Part 5. 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)

The main reasons why WordPress causes the surge in server CPU usage include plug-in problems, inefficient database query, poor quality of theme code, or surge in traffic. 1. First, confirm whether it is a high load caused by WordPress through top, htop or control panel tools; 2. Enter troubleshooting mode to gradually enable plug-ins to troubleshoot performance bottlenecks, use QueryMonitor to analyze the plug-in execution and delete or replace inefficient plug-ins; 3. Install cache plug-ins, clean up redundant data, analyze slow query logs to optimize the database; 4. Check whether the topic has problems such as overloading content, complex queries, or lack of caching mechanisms. It is recommended to use standard topic tests to compare and optimize the code logic. Follow the above steps to check and solve the location and solve the problem one by one.

Miniving JavaScript files can improve WordPress website loading speed by removing blanks, comments, and useless code. 1. Use cache plug-ins that support merge compression, such as W3TotalCache, enable and select compression mode in the "Minify" option; 2. Use a dedicated compression plug-in such as FastVelocityMinify to provide more granular control; 3. Manually compress JS files and upload them through FTP, suitable for users familiar with development tools. Note that some themes or plug-in scripts may conflict with the compression function, and you need to thoroughly test the website functions after activation.

Methods to optimize WordPress sites that do not rely on plug-ins include: 1. Use lightweight themes, such as Astra or GeneratePress, to avoid pile-up themes; 2. Manually compress and merge CSS and JS files to reduce HTTP requests; 3. Optimize images before uploading, use WebP format and control file size; 4. Configure.htaccess to enable browser cache, and connect to CDN to improve static resource loading speed; 5. Limit article revisions and regularly clean database redundant data.

TransientsAPI is a built-in tool in WordPress for temporarily storing automatic expiration data. Its core functions are set_transient, get_transient and delete_transient. Compared with OptionsAPI, transients supports setting time of survival (TTL), which is suitable for scenarios such as cache API request results and complex computing data. When using it, you need to pay attention to the uniqueness of key naming and namespace, cache "lazy deletion" mechanism, and the issue that may not last in the object cache environment. Typical application scenarios include reducing external request frequency, controlling code execution rhythm, and improving page loading performance.

PluginCheck is a tool that helps WordPress users quickly check plug-in compatibility and performance. It is mainly used to identify whether the currently installed plug-in has problems such as incompatible with the latest version of WordPress, security vulnerabilities, etc. 1. How to start the check? After installation and activation, click the "RunaScan" button in the background to automatically scan all plug-ins; 2. The report contains the plug-in name, detection type, problem description and solution suggestions, which facilitates priority handling of serious problems; 3. It is recommended to run inspections before updating WordPress, when website abnormalities are abnormal, or regularly run to discover hidden dangers in advance and avoid major problems in the future.

The most effective way to prevent comment spam is to automatically identify and intercept it through programmatic means. 1. Use verification code mechanisms (such as Googler CAPTCHA or hCaptcha) to effectively distinguish between humans and robots, especially suitable for public websites; 2. Set hidden fields (Honeypot technology), and use robots to automatically fill in features to identify spam comments without affecting user experience; 3. Check the blacklist of comment content keywords, filter spam information through sensitive word matching, and pay attention to avoid misjudgment; 4. Judge the frequency and source IP of comments, limit the number of submissions per unit time and establish a blacklist; 5. Use third-party anti-spam services (such as Akismet, Cloudflare) to improve identification accuracy. Can be based on the website

When developing Gutenberg blocks, the correct method of enqueue assets includes: 1. Use register_block_type to specify the paths of editor_script, editor_style and style; 2. Register resources through wp_register_script and wp_register_style in functions.php or plug-in, and set the correct dependencies and versions; 3. Configure the build tool to output the appropriate module format and ensure that the path is consistent; 4. Control the loading logic of the front-end style through add_theme_support or enqueue_block_assets to ensure that the loading logic of the front-end style is ensured.

To add custom user fields, you need to select the extension method according to the platform and pay attention to data verification and permission control. Common practices include: 1. Use additional tables or key-value pairs of the database to store information; 2. Add input boxes to the front end and integrate with the back end; 3. Constrain format checks and access permissions for sensitive data; 4. Update interfaces and templates to support new field display and editing, while taking into account mobile adaptation and user experience.
