细节拉满!这些小Tips(字体、线类型、标记等)让你绘图更简单~~

2022-02-17 14:53:47 浏览数 (1)

今天这篇推文,小编就对Python-matplotlib的一些基本绘图样式(字体、线类型、标记等)进行汇总统计,希望对小伙伴们有所帮助。主要内容如下:

  • matplotlib-字体属性(font properties)汇总
  • matplotlib-横线类型(line style)汇总
  • matplotlib-标记样式(Marker)汇总

matplotlib-Font Properties

这里对字体的操作只是对其斜体、粗字等属性的更改,主要从样式、粗细程度、大小。详细如下:

  • font-style:normal(正常), italic(斜体), oblique(倾斜的字体)
  • font-weight:light(细), normal(正常), medium(中等), semibold(半粗), bold(粗), heavy(特粗), black(黑)
  • font-size:xx-small(最小), x-small(较小), small(小), medium(正常(默认值)), large(大),x-large(较大), xx-large(最大)

下面小编通过可视化效果展示matplotlib的字体变化:

代码语言:javascript复制
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt

font0 = FontProperties()
alignment = {'horizontalalignment': 'center', 'verticalalignment': 'baseline'}

# 展示字体类型
styles = ['normal', 'italic', 'oblique']
t = plt.figtext(0.3, 0.9, 'style', fontproperties=font1, **alignment)

for k, style in enumerate(styles):
    font = font0.copy()
    font.set_family('sans-serif')
    font.set_style(style)
    t = plt.figtext(0.3, yp[k], style, fontproperties=font, **alignment)

# Show variant options
variants = ['normal', 'small-caps']

t = plt.figtext(0.5, 0.9, 'variant', fontproperties=font1, **alignment)

for k, variant in enumerate(variants):
    font = font0.copy()
    font.set_family('serif')
    font.set_variant(variant)
    t = plt.figtext(0.5, yp[k], variant, fontproperties=font, **alignment)

# 展示字体粗细
weights = ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']

t = plt.figtext(0.7, 0.9, 'weight', fontproperties=font1, **alignment)

for k, weight in enumerate(weights):
    font = font0.copy()
    font.set_weight(weight)
    t = plt.figtext(0.7, yp[k], weight, fontproperties=font, **alignment)

# 展示字体大小
sizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
         'x-large', 'xx-large']

t = plt.figtext(0.9, 0.9, 'size', fontproperties=font1, **alignment)

for k, size in enumerate(sizes):
    font = font0.copy()
    font.set_size(size)
    t = plt.figtext(0.9, yp[k], size, fontproperties=font, **alignment)
plt.show()

Example Of matplotlib

更多详细内容可参考:Matplotlib font 样式[1]

matplotlib-Line Style

matplotlib中线样式 使用场景较多,例如绘制图表的网格线,一般选择虚线绘制。这里小编就汇总一下matplotlib中线的样式。

  • 「名称线类型(Named linestyles)」:主要包括:实线(solid,'-')、点线(dotted,'.')、短虚线(dashed,'--')、横点线(dashdot,'-.')。
  • 「参数线类型(Parametrized linestyles)」:该类型由于不常用,可通过以下代码展示:
代码语言:javascript复制
import numpy as np
import matplotlib.pyplot as plt

linestyle_str = [
     ('solid', 'solid'),      # Same as (0, ()) or '-'
     ('dotted', 'dotted'),    # Same as (0, (1, 1)) or '.'
     ('dashed', 'dashed'),    # Same as '--'
     ('dashdot', 'dashdot')]  # Same as '-.'

linestyle_tuple = [
     ('loosely dotted',        (0, (1, 10))),
     ('dotted',                (0, (1, 1))),
     ('densely dotted',        (0, (1, 1))),

     ('loosely dashed',        (0, (5, 10))),
     ('dashed',                (0, (5, 5))),
     ('densely dashed',        (0, (5, 1))),

     ('loosely dashdotted',    (0, (3, 10, 1, 10))),
     ('dashdotted',            (0, (3, 5, 1, 5))),
     ('densely dashdotted',    (0, (3, 1, 1, 1))),

     ('dashdotdotted',         (0, (3, 5, 1, 5, 1, 5))),
     ('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
     ('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))]


def plot_linestyles(ax, linestyles, title):
    X, Y = np.linspace(0, 100, 10), np.zeros(10)
    yticklabels = []

    for i, (name, linestyle) in enumerate(linestyles):
        ax.plot(X, Y i, linestyle=linestyle, linewidth=1.5, color='black')
        yticklabels.append(name)

    ax.set_title(title)
    ax.set(ylim=(-0.5, len(linestyles)-0.5),
           yticks=np.arange(len(linestyles)),
           yticklabels=yticklabels)
    ax.tick_params(left=False, bottom=False, labelbottom=False)
    for spine in ["left",'top',"right",'bottom']:
        #ax.spines[:].set_visible(False)
        ax.spines[spine].set_visible(False)

    # For each line style, add a text annotation with a small offset from
    # the reference point (0 in Axes coords, y tick value in Data coords).
    for i, (name, linestyle) in enumerate(linestyles):
        ax.annotate(repr(linestyle),
                    xy=(0.0, i), xycoords=ax.get_yaxis_transform(),
                    xytext=(-6, -12), textcoords='offset points',
                    color="blue", fontsize=8, ha="right", family="monospace")


ax0, ax1 = (plt.figure(figsize=(10, 8))
            .add_gridspec(2, 1, height_ratios=[1, 3])
            .subplots())

plot_linestyles(ax0, linestyle_str[::-1], title='Named linestyles')
plot_linestyles(ax1, linestyle_tuple[::-1], title='Parametrized linestyles')

plt.tight_layout()
plt.show()

Example Of matplotlib linstyles

更多详细内容可参考:Matplotlib 线类型[2]

matplotlib-Marker

matplotlib提供了多种marker类型用于绘制不同的图表类型,下面从Filled markers、Unfilled markers以及Marker fill styles 三种常用marker进行展示,详细如下:

「filled markers」:

代码语言:javascript复制
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D


text_style = dict(horizontalalignment='right', verticalalignment='center',
                  fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
                    markerfacecolor="#BC3C28", markeredgecolor="black")
                    
def format_axes(ax):
    ax.margins(0.2)
    ax.set_axis_off()
    ax.invert_yaxis()

def split_list(a_list):
    i_half = len(a_list) // 2
    return a_list[:i_half], a_list[i_half:]
    
##filled markers
fig, axs = plt.subplots(ncols=2,facecolor="white",figsize=(5,4),dpi=100)
fig.suptitle('Filled markers', fontsize=14)
for ax, markers in zip(axs, split_list(Line2D.filled_markers)):
    for y, marker in enumerate(markers):
        ax.text(-0.5, y, repr(marker), **text_style)
        ax.plot([y] * 3, marker=marker, **marker_style)
    format_axes(ax)
plt.show()

Example Of Matplotlib Filled markers

「Unfilled markers」:

代码语言:javascript复制
fig, axs = plt.subplots(ncols=2,facecolor="white",figsize=(5,4),dpi=100)
fig.suptitle('Un-filled markers', fontsize=14)

# Filter out filled markers and marker settings that do nothing.
unfilled_markers = [m for m, func in Line2D.markers.items()
                    if func != 'nothing' and m not in Line2D.filled_markers]

for ax, markers in zip(axs, split_list(unfilled_markers)):
    for y, marker in enumerate(markers):
        ax.text(-0.5, y, repr(marker), **text_style)
        ax.plot([y] * 3, marker=marker, **marker_style)
    format_axes(ax)
plt.show()

Example Of Matplotlib Unfilled markers

「Marker fill styles」:

代码语言:javascript复制
fig, ax = plt.subplots(facecolor="white",figsize=(6,4),dpi=100)
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)

filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
                           color='#868686',
                           markerfacecolor='#EFC000',
                           markerfacecoloralt='lightsteelblue',
                           markeredgecolor='brown')

for y, fill_style in enumerate(Line2D.fillStyles):
    ax.text(-0.5, y, repr(fill_style), **text_style)
    ax.plot([y] * 3, fillstyle=fill_style, **filled_marker_style)
format_axes(ax)
plt.show()

Example Of Matplotlib Marker fill styles

以上就是小编对matplotlib marker的一个简单汇总,更多详细内容可参考:Matplotlib Marker介绍[3]

总结

这篇推文小编简单汇总了Python-matplotlib中字体属性(font properties)、线类型(line styles)、标记样式(Marker styles),当作自己的一个学习自留地,同时也希望能够帮助到需要的小伙伴,后期会不定期汇总这种常见易忘记的绘图技巧哈~

参考资料

[1]Fonts demo: https://matplotlib.org/stable/gallery/text_labels_and_annotations/fonts_demo.html#sphx-glr-gallery-text-labels-and-annotations-fonts-demo-py。

[2]Linestyles: https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html#sphx-glr-gallery-lines-bars-and-markers-linestyles-py。

[3]Marker reference: https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html#sphx-glr-gallery-lines-bars-and-markers-marker-reference-py。

0 人点赞