This is the 16th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

preface

It is well known that matplotlib.pyplot provides methods for plotting different tables, such as using plot() to plot broken lines, bar() to plot bars, hist() to plot histograms, and so on. See the links below for details on their use.

  • Matplotlib Line chart: Summarize the properties of the line chart

  • Matplotlib Bar chart drawing: Summarize the properties of a bar chart

  • Matplotlib Histogram drawing: Summary and description of histogram properties

  • Matplotlib: Describes the properties of the scatter diagram

  • Matplotlib drawing contour map: Summarize and explain the properties of contour map

There is also a chart in Matplotlib. pyplot that is used to visually illustrate pie charts and there are many examples of pie charts on matplotlib’s website.

In this installment, we will learn matplotlib to draw pie chart related properties in detail, let’s go~

1. Outline of contour map

  • What is a pie chart?

    • Pie charts show the size of items in a circle in proportion to the sum of total items
    • The pie chart shows the proportion of items by different sizes
    • Data markers of the same color in the pie chart form a data series
    • The pie chart can be divided into three dimensional pie chart, composite pie chart and separated pie chart
  • Common pie chart scenarios

    • Pie charts are available where temporary proportions of constituent parts are needed
    • The pie chart reflects the proportion of each indicator in a dimension in the overall situation
    • Pie charts are good for looking at the overall ratio, not the accuracy of the data
  • Draw equal pie chart steps

    1. Import the matplotlib.pyplot module
    2. To prepare data, use numpy/ PANDAS
    3. Call Pyplot.pie () to draw a pie chart
    4. Call the Axis method to adjust the spacing between x and y axes
  • The case shows

    In this issue, we will analyze operating system market share using pie charts

    • Case data preparation: Use random. Randint to produce 5 values

      import numpy as np
      size = np.random.randint(0.100.5)
      Copy the code
    • Draw the pie chart

      import matplotlib.pyplot as plt\
      
      plt.pie(size,labels=["Windows"."MAC"."Linux"."Android"."Other"])
      
      plt.title("Mobile system share Analysis")
      
      plt.show()
      Copy the code

2. Pie chart properties

  • Sets the color of the pie chart

    • Keyword: colors
    • Options: None or color list
    • A color list can be composed of the following:
      • Words for colors: e.g. Red, “red”
      • Short for color words such as red “r”, yellow “Y”
      • RGB format: hexadecimal format, such as “# 88C999 “; (r,g,b) tuple form
  • Set up the label

    • Keyword: labels
    • The default is None
    • You need to pass in a list of values
  • Set highlights

    • Key word: explode
    • The default is None
    • You need to pass in list data
    • If the value is set, the specified part is highlighted
  • Set the fill in percentage value

    • Key words: autopct
    • The default is None
    • Optional value form:
      • Format strings such as ‘%1.1f%%’
      • Function: Function content can be called
  • The pie chart rotation

    • Counterclockwise rotation Angle from x axis: startAngle; The default is 0 and is of floating point type
    • Specifies the direction of the score clockwise: counterclock; The default is True, bool
  • Set the shadow

    • Key word: shadow
    • The default is False
    • Draw shadows under the pie chart
  • Let’s add some attributes based on the example in section 1. We need to display the percentage value, color display the specified color, and highlight the MAC percentage

    plt.pie(size,labels=["Windows"."MAC"."Linux"."Android"."Other"],
    autopct="% 1.1 f % %",
    explode=[0.0.1.0.0.0],
    colors=("r"."blue"."#88c999", (1.1.0),"0.5"))
    Copy the code

3. Resize the pie chart

When we actually make the pie chart, we will encounter changing the size of the pie chart, which we can use the pie chart attribute keyword RADIUS

  • Radius: Sets the radius of the pie chart

In addition, we also use Textprops to control the size of the tag to display

plt.pie(size,labels=["Windows"."MAC"."Linux"."Android"."Other"],autopct="% 1.1 f % %",
explode=[0.0.1.0.0.0],
colors=("r"."blue"."#88c999", (1.1.0),"0.5"),radius=0.5,textprops={'size':"smaller"})
Copy the code

4. Add legends

When the pie chart shows the proportions of each item, we add a set of legends next to the chart.

  • The pyplot.pie() method returns patchee.wedge lists, text lists, and so on
  • The pyplot.Legend () method passes in the wedge element and the specified Labels
  • You can also set the legend location with the legend() method bbox_to_anchor
La = ["Windows"."MAC"."Linux"."Android"."Other"]

def f(pct,n) :
    num = int(round(pct*np.sum(n)))
    return "{:.1f}%\n{:d}w".format(pct,num)

wedges ,text,autotexts =plt.pie(size,autopct=lambda pct: f(pct,size),
        colors=("r"."blue"."#88c999", (1.1.0),"0.5"),textprops=dict(color='w'))

plt.legend(wedges,La,loc="right",bbox_to_anchor=(1.0.0.3.1))
Copy the code

5. Hollow out pie chart

In pie charts, we sometimes use nested and hollow pie charts.

  • The nested Pyplot.pie () method can be called multiple times
  • Hollowing can be set with the Pyplot.pie () property Wedgeprops
  • Wedgeprops = {” width “, 0.3, “edgecolor” : ‘w’}
cmap = plt.get_cmap("tab20c")
plt.pie(size,
         colors=("r"."blue"."#88c999", (1.1.0),"0.5"),textprops=dict(color='w'),wedgeprops=dict(width=0.3,edgecolor='w'))
plt.pie(size,
         colors= cmap(np.arange(3) *5),radius=0.7,wedgeprops=dict(width=0.3,edgecolor='w'),textprops={'size':"smaller"})
Copy the code

conclusion

In this installment, learn about attributes related to plotting pie() by matplotlib.pyplot. When drawing the pie chart, we will change the size of the pie chart according to the actual demand, nest the pie chart, add bar chart and other graphs to assist in viewing

That’s the content of this episode. Please give us your thumbs up and comments. See you next time