This is the sixth day of my participation in the August Text Challenge.More challenges in August

Hello, everyone, I am the talented brother.

Waffle Chart, or rectangular pie Chart, can visually depict the percentage completion ratio. Compared to traditional pie charts, waffle charts express percentages more clearly and accurately, with each grid representing 1%. A typical use of the Waffle chart is to compare the completion ratio of the same type of indicator. For example, job completion, annual revenue schedule, etc.

1. Excel draws waffle charts

In fact, there are many ways to draw waffle charts with Excel. One of the more complicated ways is to adjust the bar chart specifications after inserting the bar chart. Another simpler operation is to take the form of a cell format, and this is the solution we will introduce today.

1.1. Effect preview

1.2. Implementation steps

Select the 10 x 10 range of 100 cells and set the width and height pixels of the cells to equal values, which we set to 25 pixels

We then fill in the numbers 1-100 from left – > right and bottom – > top in the cell

To display the progress value, we enter the value at the bottom (66% for example), and then select the 10 × 10 numeric area for conditional formatting – > Icon Set – > Shape

Finally, enter conditional formatting again to select a management rule to set detailed rules. After clicking a specific rule, you can click edit rule or double-click a specific rule

The specific rules are as follows:

  • Type selection formula
  • Cells that exceed the specified value (in this case, C13 66%*100) are grayed out
  • Cells that do not exceed the specified value are orange-red
  • Also remember to check to show only ICONS (otherwise cell numbers will show overlying ICONS)

Once the rules are determined, we can see that they look like this, and we are done with simple optimizations (such as removing the grid and adding other elements)

2. Python draws waffle charts

Pywaffle is a third party library designed to draw waffle charts.

Old rule, install before use:

pip install pywaffle
Copy the code

This is followed by a simple drawing process:

import matplotlib.pyplot as plt
from pywaffle import Waffle
# Set Chinese font
plt.rcParams["font.family"] = "Microsoft YaHei"
# progress values
value = 0.66
values = [value,1-value]
fig = plt.figure(
    FigureClass=Waffle,
    rows=10.# 10 lines
    columns=10.# 10 column
    values=values, # value
    colors=["#FF4500"."#C0C0C0"].# color
    vertical=True.Set the drawing direction from bottom up and left to right
    characters=The '*'.# Use solid circles for ICONS
    font_size=45.The size is 45
    title={
        'label': 'Job completion'.Set the chart title
        'loc': 'center'.'y':1.05.'fontdict': {
            'fontsize': 20
    }
},
)
fig.text( # Set the progress value display
    x=0.3,
    y=-0.03,
    s=f"{int(100*value)}%",
    ha="center",
    va="center",
    fontsize=25,
    color='orangered'.# orange red
)
Copy the code

The drawing output is as follows:

3. Introduction to pywaffle charts

Since features are waffle charts, the content is not complicated and you can refer directly to the official documentation (features and cases are both relatively simple).

# official website addresshttps://pywaffle.readthedocs.io/
Copy the code

Waffle Chart, also known as Square Pie Chart, is a variation of the Pie Chart that is good at showing the proportion of parts in the whole. In general, a waffle chart is made up of 100 cells, with one cell representing 1%. Different color grids are used to distinguish different categories of data to show the proportion of each component in the whole.

3.1. Basic cases

Introduce matplotlib and PyWaffle, specify FigureClass=Waffle when drawing

import matplotlib.pyplot as plt
from pywaffle import Waffle

plt.figure(
    FigureClass=Waffle,
    rows=5.# lines
    columns=10.# the number of columns
    values=[30.16.4] # number of rows and columns =50 # number of rows and columns =50
)
plt.show()
Copy the code

The values parameter also accepts data from the dictionary, whose keys will be used as labels and displayed in the legend

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    columns=10,
    values={'Cat1': 30.'Cat2': 16.'Cat3': 4},
    legend={ # legend
        'loc': 'upper left'.# legend position
        'bbox_to_anchor': (1.1) # legend position coordinates})Copy the code

3.2. Numerical scaling

Set the value of the rounding_rule parameter to specify a scaling rule when the total number of cells and the total number of digits in values are not equal.

When rounding_rule is ceil or nearest, the sum of the zoom values may be greater than the total number of squares. If so, the grid for the last category will not be fully displayed. Thus, while nearest is the default rounding rule, floor is actually the most consistent rule because it avoids grid overflow.

In the following example, the values are scaled to 24, 23, 1 for the cell numbers and rounding_rule= floor

plt.figure(
    FigureClass=Waffle,
    rows=5,
    columns=10,
    values=[48.46.3],
    rounding_rule='floor'
)
Copy the code

Of course, it is also possible to adjust the number of cells automatically by setting only one row and one parameter value:

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[48.46.3],)Copy the code

3.3. Headings, labels and legends

Title parameter, labels parameter, legend parameter. The meanings of these parameters are the same as those in matplotlib. For details, see matplotlib.

data = {'Cat1': 30.'Cat2': 16.'Cat3': 4}
fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    columns=10,
    values=data,
    title={
        'label': 'Example plot'.'loc': 'left'.'fontdict': {
            'fontsize': 20
        }
    },
    labels=[f"{k} ({int(v / sum(data.values()) * 100)}%)" for k, v in data.items()],
    legend={
        # 'labels': [f"{k} ({v}%)" for k, v in data.items()], # lebels could also be under legend instead
        'loc': 'lower left'.'bbox_to_anchor': (0, -0.2),
        'ncol': len(data),
        'framealpha': 0.'fontsize': 12})Copy the code

3.4. Grid color

The colors argument accepts the colors in a list or tuple, and its length must be the same values. Also, we can specify Colormap by setting parameter cmap_name.

Specify color colors

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    columns=10,
    values=[30.16.4],
    colors=["# 232066"."#983D3D"."#DCB732"])Copy the code

Specify cmap_name

Only qualitative color maps are supported, including Pastel1, Pastel2, Paired, Accent, Dark2, Set1, Set2, Set3, TAB10, TAB20, TAB20b, and TAB20C.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    columns=10,
    values=[30.16.4],
    cmap_name="Accent"
)
Copy the code

3.5. Fill the grid with characters or ICONS

character

By passing a list or tuple of characters to an argument, a category can have a different character, characters, and values for each category. Sometimes you need to specify a font if the default font is not supported. Pass the absolute path of the.ttf or.otf file to font_file.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4],
    colors=["#4C8CB5"."#B7CBD7"."#C0C0C0"],
    characters=The '*',
    font_size=24
)
Copy the code

icon

PyWaffle supports drawing using the Font Awesome icon

fontawesome.com/

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4],
    colors=["# 232066"."#983D3D"."#DCB732"],
    icons='star',
    font_size=24
)
Copy the code

By passing a list or tuple of icon names to the parameter, each category can have different ICONS whose length must be the same as values.

In Font Awesome Icons, there are different sets of Icons in different styles, including Solid, Regular and Brands. Icon_style can be specified with a parameter. By default, it searches for ICONS from the solid style.

Using icon_legend= True, the symbols in the legend will be ICONS. Otherwise, it will be a color bar.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4],
    colors=["#FFA500"."#4384FF"."#C0C0C0"],
    icons=['sun'.'cloud-showers-heavy'.'snowflake'],
    font_size=20,
    icon_style='solid',
    icon_legend=True,
    legend={
        'labels': ['Sun'.'Shower'.'Snow'].'loc': 'upper left'.'bbox_to_anchor': (1.1)})Copy the code

Font Awesome Icons locate Icons by style and icon name. Different styles contain different sets of ICONS. Therefore, the icon_style of all ICONS may not be the same. In this case, icon_style can be either a list or a style tuple.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4],
    colors=["#FFA500"."#4384FF"."#C0C0C0"],
    icons=['sun'.'cloud-showers-heavy'.'font-awesome-flag'],
    icon_size=20,
    icon_style=['regular'.'solid'.'brands'],
    icon_legend=False,
    legend={
        'labels': ['Sun'.'Shower'.'Flag'].'loc': 'upper left'.'bbox_to_anchor': (1.1)})Copy the code

3.6. Other attributes of the grid

Other attributes of the grid include the shape of the grid to draw, spacing, starting position, and drawing direction.

Grid color

The block_aspect_ratio parameter controls the shape of a grid by changing the ratio of its width to its height. By default it is 1, so the grid is square.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4],
    block_aspect_ratio=1.618
)
Copy the code

spacing

The parameters interval_ratio_x and interval_ratio_y control the horizontal and vertical distances between cells. Interval_ratio_y is the ratio of the vertical distance between the cells to the height of the cells.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4],
    interval_ratio_x=1,
    interval_ratio_y=0.5
)
Copy the code

The starting position

Use the parameter starting_location to set the location of the start grid. It accepts positions in a string, such as NW, SW,NE, and SE for the four corners. By default, it is SW, which means that PyWaffle draws the grid from the bottom left corner.

Here is an example of drawing from the bottom right (SE) :

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4],
    starting_location='SE'
)
Copy the code

The drawing direction

By default, PyWaffle draws the grid column by column, so the categories are drawn horizontally. To make it vertical, set the parameter vertical to True.

In the following example, it draws the grid from the bottom left to the bottom right of the row to the top:

3.7. Other

Adjust graphics size, background color, DPI, etc

Figsize, DPI, Facecolor, tight_layout, etc

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4],
    colors=["# 232066"."#983D3D"."#DCB732"],
    facecolor='#DDDDDD'  # facecolor is a parameter of matplotlib.pyplot.figure
)
Copy the code

Add other elements

In the example below, we use the text() method to add a custom watermark to the graph

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30.16.4]
)
fig.text(
    x=0.5,
    y=0.5,
    s="You can call me genius.",
    ha="center",
    va="center",
    rotation=30,
    fontsize=40,
    color='gray',
    alpha=0.3,
    bbox={
        'boxstyle': 'square'.'lw': 3.'ec': 'gray'.'fc': (0.9.0.9.0.9.0.5), 
        'alpha': 0.3})Copy the code