Table of Contents
Creating pie charts in Plotly.js
在 Plotly.js 中创建仪表图表
最终想法
Home CMS Tutorial WordPress Pie and Gauge Charts: Unlocking Interactivity with Plotly.js, Part 5

Pie and Gauge Charts: Unlocking Interactivity with Plotly.js, Part 5

Aug 31, 2023 pm 08:53 PM

饼图和仪表图:使用 Plotly.js 解锁交互性,第 5 部分

If 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);
Copy after login

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);
Copy after login

在 Plotly.js 中创建仪表图表

仪表图的基本结构与圆环图类似。这意味着我们可以使用一些巧妙选择的值并通过仍然将 type 属性设置为 pie 来创建简单的仪表图表。基本上,我们将隐藏整个饼图的某些部分,使其看起来像仪表图。

首先,我们需要为 values 属性选择一些值。为了简单起见,我将使用饼图的上半部分作为我的仪表图。这意味着这些值应该在我想要可见的部分和我想要隐藏的饼图部分之间平均分配。图表的可见部分可以进一步分为更小的部分。以下是为仪表图表选择值的示例。

values: [100 / 5, 100 / 5, 100 / 5, 100 / 5, 100 / 5, 100]
Copy after login

上行中的数字 100 是任意的。可以看到,前五个切片加起来是100,这也是为饼图隐藏区域设置的值。这将整个馅饼平均分为隐藏部分和可见部分。

这是创建基本仪表图表的完整代码。您应该注意到,我已将应隐藏的扇区的颜色属性设置为白色。同样,相应扇区的 textlabels 值也已设置为空字符串。 rotation 属性已设置为 90,以便图表不会从默认的 12 点钟位置绘制。

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"
};
Copy after login

代码的下一部分涉及仪表图表的指针。您为 Degrees 变量设置的值将确定绘制针的角度。 radius 变量决定针的长度。属性 x0y0 用于设置线条的起点。同样,属性 x1y1 用于设置线条的终点。

您可以借助 SVG 路径为针创建更复杂的形状。您所要做的就是将 type 属性设置为 path 并使用 path 属性指定实际路径。您可以在参考的布局形状部分阅读更多相关信息。

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});
Copy after login

本节的所有代码都会创建以下仪表图表。目前,该图表不是很奇特,但它可以作为一个很好的起点。

最终想法

在本教程中,您学习了如何使用 Plotly.js 中的 pie 跟踪类型创建饼图和圆环图。您还学习了如何仔细设置一些属性的值,以将这些饼图转换为简单的仪表图。您可以在参考页面上阅读有关饼图及其不同属性的更多信息。

这是我们的交互式 Plotly.js 图表系列的最后一个教程。第一个介绍性教程为您提供了该库的概述。第二、第三和第四教程分别向您展示了如何创建折线图、条形图和气泡图。我希望您喜欢本教程以及整个系列。如果您有任何疑问,请随时在评论中告诉我。

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1263
29
C# Tutorial
1237
24
How to adjust the wordpress article list How to adjust the wordpress article list Apr 20, 2025 am 10:48 AM

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners How To Begin A WordPress Blog: A Step-By-Step Guide For Beginners Apr 17, 2025 am 08:25 AM

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

How to get logged in user information in WordPress for personalized results How to get logged in user information in WordPress for personalized results Apr 19, 2025 pm 11:57 PM

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo();  function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

How to display child categories on archive page of parent categories How to display child categories on archive page of parent categories Apr 19, 2025 pm 11:54 PM

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

How to sort posts by post expiration date in WordPress How to sort posts by post expiration date in WordPress Apr 19, 2025 pm 11:48 PM

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

How to Automate WordPress and Social Media with IFTTT (and more) How to Automate WordPress and Social Media with IFTTT (and more) Apr 18, 2025 am 11:27 AM

Are you looking for ways to automate your WordPress website and social media accounts? With automation, you will be able to automatically share your WordPress blog posts or updates on Facebook, Twitter, LinkedIn, Instagram and more. In this article, we will show you how to easily automate WordPress and social media using IFTTT, Zapier, and Uncanny Automator. Why Automate WordPress and Social Media? Automate your WordPre

How to display query count and page loading time in WordPress How to display query count and page loading time in WordPress Apr 19, 2025 pm 11:51 PM

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

How to build a website for wordpress host How to build a website for wordpress host Apr 20, 2025 am 11:12 AM

To build a website using WordPress hosting, you need to: select a reliable hosting provider. Buy a domain name. Set up a WordPress hosting account. Select a topic. Add pages and articles. Install the plug-in. Customize your website. Publish your website.

See all articles