Contrast excel, draw waffle chart with python

1. Excel to draw a waffle chart

In fact, there are many ways to draw a waffle chart with excel. The more complicated one is to adjust the specification of the histogram after inserting the histogram chart. Another relatively simple operation is 单元格格式the form that we will introduce today. plan.

1.1. Effect preview

1.2. Implementation steps

First select 10*10a total of 100 cell ranges, and then set the width and height pixels of the cells to the same value, here we set the value to 25 pixels

Then we fill in the numbers in the cells from left -> right , bottom -> top1-100

In order to display the progress value, we enter the value at the bottom (66% is used here as an example), and then select the 10*10 digital area to 条件格式set it —> 图标集—>形状

Finally, enter the conditional formatting settings again and select the management rule for detailed rule setting. After clicking the specific rule, you can click Edit rule or double-click the specific rule directly.

The specific rules are as follows:

  • Type selection formula
  • If the cell value exceeds the specified value (here is C13 cell 66%*100), it will be grayed out
  • If the cell value does not exceed the specified value, it will be orange-red
  • At the same time, remember to check only display icons (otherwise, there will be a case where the cell numbers display overlay icons)

After determining the rules, we can see that the effect is as follows, and we are done with simple optimization (such as removing grids and adding other elements)

2. Python draw waffle chart

This is a third-party library pywaffle. You can see from the name of this library that it is specially used to draw waffle charts.

Old rules, first install and then use:

pip install pywaffle

Then there is the simple drawing process:

import matplotlib.pyplot as plt
from pywaffle import Waffle
# 设置中文字体
plt.rcParams["font.family"] = "Microsoft YaHei"
# 进度值
value = 0.66
values = [value,1-value]
fig = plt.figure(
    FigureClass=Waffle,
    rows=10, # 10行
    columns=10, # 10列
    values=values, # 值
    colors=["#FF4500", "#C0C0C0"], # 配色
    vertical=True, # 设置绘图方向从下往上、从左往右
    characters='●', # 用实心圆做图标
    font_size=45, # 大小为45
    title={
        'label': '工作完成度', # 设置图表标题
        'loc': 'center',
        'y':1.05,
        'fontdict': {
            'fontsize': 20
    }
},
)
fig.text( # 设置进度值显示
    x=0.3,
    y=-0.03,
    s=f"{int(100*value)}%",
    ha="center",
    va="center",
    fontsize=25,
    color='orangered', # 橙红色
)

The plot output is as follows:

3. pywaffle waffle chart introduction

Since the function is a waffle chart, the content is not complicated, and you can directly refer to the official documentation (both functions and cases are available, and they are relatively simple).

# 官网地址
https://pywaffle.readthedocs.io/

Waffle Chart , also known as Waffle Chart Square Pie Chart, is a variant of pie chart, which is good at showing the proportion of parts in the whole . Generally speaking, a waffle chart is composed of 100 grids, one grid represents 1%. Use different colored grids to distinguish different categorical data to show the proportion of each part in the whole.

3.1. Base case

Introduce matplotliband pywaffle, specify when FigureClass=Waffledrawing

import matplotlib.pyplot as plt
from pywaffle import Waffle

plt.figure(
    FigureClass=Waffle,
    rows=5, # 行数
    columns=10,  # 列数
    values=[30, 16, 4] # 值(三类值,这里总和=50和格子总数相等,则行列可以只指定一个即可)
)
plt.show()

The parameter valuesalso accepts data from a dictionary, the keys of the dictionary 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={ # 图例
        'loc': 'upper left', # 图例位置
        'bbox_to_anchor': (1, 1) # 图例位置坐标
    }
)

3.2. Numerical scaling

When the total number of grids and the sum of the numbers in values ​​are not equal, setting rounding_rulethe value of the parameter can specify the scaling rule.

When rounding_ruleeither ceilor nearest, the sum of the scaling values ​​may be greater than the total number of cells. If so, the last category grid will not be fully displayed. So, while nearestthe default rounding rule, flooris actually the most consistent rule because it avoids lattice overflow.

In the following example, the values ​​are scaled to 24, 23, 1 as the grid number and use rounding_rule=floor

plt.figure(
    FigureClass=Waffle,
    rows=5,
    columns=10,
    values=[48, 46, 3],
    rounding_rule='floor'
)

Of course, the number of grids can also be automatically adjusted by setting only one row and one parameter value:

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[48, 46, 3],
)

3.3. Titles, labels and legends

title parameter title, label parameter labels, legend parameter legend. The meanings of these parameters are the same as those in matplotlib. For details, please refer to the corresponding introduction of 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
    }
)

3.4. Checker Color

The parameter colorsaccepts colors in a list or tuple, which must be the same length as values. At the same time, we can also cmap_namespecify by setting parameters Colormap.

Specify the colors colors

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    columns=10,
    values=[30, 16, 4],
    colors=["#232066", "#983D3D", "#DCB732"]
)

specify cmap_name

Only qualitative colormaps are supported, including Pastel1, Pastel2, Paired, Accent, Dark2, Set1, Set2, Set3, tab10, tab20, tab20b, tab20c.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    columns=10,
    values=[30, 16, 4],
    cmap_name="Accent"
)

3.5. Fill the grid with characters or icons

character

Categories can have different characters for each category by passing a list or tuple of characters to the argument, which charactersmust be the same length as values. Sometimes it is found that the default font is not supported, you need to specify the font, please pass the absolute path of the .ttf or .otf file to the parameter font_file.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30, 16, 4],
    colors=["#4C8CB5", "#B7CBD7", "#C0C0C0"],
    characters='●',
    font_size=24
)

icon

PyWaffle supports Font Awesome 图标drawing using

fontawesome.com/

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30, 16, 4],
    colors=["#232066", "#983D3D", "#DCB732"],
    icons='star',
    font_size=24
)

Each category can have a different icon by passing a list or tuple of icon names to the parameter, which iconsmust be the same length as values.

In Font Awesome Icons, there are different icon sets in different styles, including Solid, Regular and Brands. Can be set via parameter specification icon_style, by default it solidsearches for icons from styles.

With icon_legend= True, the symbols in the legend will be icons. Otherwise, it will be a colorbar.

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)
    }
)

Font Awesome Icons locates icons by style and icon name. Different styles contain different icon sets. Therefore, the icon_style may not be the same for all icons. In this case, it icon_stylecan be 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)
    }
)

3.6. Other properties of the grid

Other properties of the grid include the drawn grid shape, spacing, starting position, and drawing direction.

plaid color

Parameters block_aspect_ratiocontrol the shape of the grid by changing the width to height ratio of the grid. 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
)

spacing

Parameter interval_ratio_xand interval_ratio_ycontrols the horizontal and vertical distance between grids. interval_ratio_xis the ratio of the horizontal distance between the grids to the grid width interval_ratio_y, and is the ratio of the vertical distance between the grids to the grid height.

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30, 16, 4],
    interval_ratio_x=1,
    interval_ratio_y=0.5
)

starting point

Use the parameter starting_locationto set the position of the starting grid. It accepts a position in a string, such as NW, SW, NEand SErepresents the four corners. By default, it is SW, which means PyWaffle draws the lattice starting from the bottom left corner.

Here is SEan example of drawing starting from the bottom right corner ( ):

fig = plt.figure(
    FigureClass=Waffle,
    rows=5,
    values=[30, 16, 4],
    starting_location='SE'
)

drawing direction

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

In the example below, it draws the lattice from the bottom left corner to the bottom right corner until the top:

3.7. Others

Adjust graphics size, background color, DPI, and more

Like figsize, dpi, facecolor, tight_layoutetc. can be set, set the background color as follows

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
)

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="可以叫我才哥",
    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
    }
)

Today's content is shared here, and the editor finally prepared a python spree for everyone [Jiajun Yang: 419693945] to help everyone learn better!

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324341459&siteId=291194637