当前位置: 首页 > article >正文

Python 中常见的一些画图形式

文章目录

  • Python 中常见的一些画图形式
    • 颜色参数
    • 直线参数
    • 标记参数
    • 画3D图

Python 中常见的一些画图形式

颜色参数

显示Python中不同的颜色

import math
from matplotlib.patches import Rectangle
import numpy as np
from matplotlib import pyplot as plt
# 颜色说明
import matplotlib.colors as mcolors

def plot_colortable(colors, *, ncols=4, sort_colors=True):

    cell_width = 212
    cell_height = 22
    swatch_width = 48
    margin = 12

    # Sort colors by hue, saturation, value and name.
    if sort_colors is True:
        names = sorted(
            colors, key=lambda c: tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(c))))
    else:
        names = list(colors)

    n = len(names)
    nrows = math.ceil(n / ncols)

    width = cell_width * ncols + 2 * margin
    height = cell_height * nrows + 2 * margin
    dpi = 72

    fig, ax = plt.subplots(figsize=(width / dpi, height / dpi), dpi=dpi)
    fig.subplots_adjust(margin/width, margin/height,
                        (width-margin)/width, (height-margin)/height)
    ax.set_xlim(0, cell_width * ncols)
    ax.set_ylim(cell_height * (nrows-0.5), -cell_height/2.)
    ax.yaxis.set_visible(False)
    ax.xaxis.set_visible(False)
    ax.set_axis_off()

    for i, name in enumerate(names):
        row = i % nrows
        col = i // nrows
        y = row * cell_height

        swatch_start_x = cell_width * col
        text_pos_x = cell_width * col + swatch_width + 7

        ax.text(text_pos_x, y, name, fontsize=14,
                horizontalalignment='left',
                verticalalignment='center')

        ax.add_patch(
            Rectangle(xy=(swatch_start_x, y-9), width=swatch_width,
                      height=18, facecolor=colors[name], edgecolor='0.7')
        )

    return fig


# 有8种颜色
# ['k', 'w', 'r', 'y', 'g', 'c', 'b', 'm']
# 黑色,白色,红色,黄色,绿色,青色,蓝色,品红色
# colors = mcolors.BASE_COLORS
# 有10种颜色
# ['gray','brown','orange','olive','green','cyan','blue','purple','pink','red']
# '灰色', '棕色', '橙色', '橄榄色', '绿色', '青色', '蓝色', '紫色', '粉红色', '红色'
colors = mcolors.TABLEAU_COLORS
# 有 148 种颜色
# colors = mcolors.CSS4_COLORS
# 有 949 种颜色
# colors = mcolors.XKCD_COLORS
names = sorted(colors, key=lambda c: tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(c))))


plot_colortable(mcolors.BASE_COLORS, ncols=3, sort_colors=False)
plt.show()

plot_colortable(mcolors.TABLEAU_COLORS, ncols=3, sort_colors=False)
plt.show()

plot_colortable(mcolors.CSS4_COLORS, ncols=3, sort_colors=False)
plt.show()

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

举例说明

color_list = ['k', 'w', 'r', 'y', 'g', 'c', 'b', 'm', 'gray','brown','orange','olive','green','cyan','blue','purple','pink','red']
x = np.random.rand(len(color_list))
y = np.random.rand(len(color_list))
for i in range(len(color_list)):
	plt.plot(x[i],y[i],  color = color_list[i], markersize=12, marker='*')
plt.xlabel('x', fontsize=12)
plt.ylabel('y', fontsize=12)
plt.xlim(left = 0, right = 1)
plt.ylim(bottom = 0, top = 1)
# 设置轴刻度 ,matplotlib将刻度放在对应范围的哪个位置,默认情况下这些刻度就是刻度标签;
plt.xticks(np.linspace(0, 1, 5))
plt.yticks(np.linspace(0, 1, 5))
plt.show()

在这里插入图片描述

直线参数

显示Python中支持的不同直线线型

import matplotlib.pyplot as plt
import numpy as np

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

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

     ('long dash with offset', (5, (10, 3))),
     ('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)
    ax.spines[:].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")


fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(7, 8), height_ratios=[1, 3],
                               layout='constrained')

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

plt.show()

在这里插入图片描述

举例说明

line_list = ['-', '--', '-.', ':', 'solid', 'dashed', 'dashdot', 'dotted']
# line_list = ['solid', 'dashed', 'dashdot', 'dotted']
for i in range(len(line_list)):
	x = np.linspace(0, 10, 10)
	y = [i] * 10
	plt.plot(x, y, linestyle=line_list[i], linewidth=2,label = line_list[i])
plt.legend()
plt.show()

在这里插入图片描述

标记参数

import matplotlib.pyplot as plt

from matplotlib.lines import Line2D
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import Affine2D

text_style = dict(horizontalalignment='right', verticalalignment='center',
                  fontsize=12, fontfamily='monospace')
marker_style = dict(linestyle=':', color='0.8', markersize=10,
                    markerfacecolor="tab:blue", markeredgecolor="tab:blue")


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:]

fig, axs = plt.subplots(ncols=2)
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()

fig, axs = plt.subplots(ncols=2)
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()


fig, ax = plt.subplots()
fig.suptitle('Marker fillstyle', fontsize=14)
fig.subplots_adjust(left=0.4)
filled_marker_style = dict(marker='o', linestyle=':', markersize=15,
                           color='darkgrey',
                           markerfacecolor='tab:blue',
                           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()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

举例说明

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)
unfilled_markers_list_1 = [',','1','2','3','4', '+', 'x', '|', '_']
unfilled_markers_list_2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
x = np.random.rand(len(unfilled_markers_list_1))
y = np.random.rand(len(unfilled_markers_list_1))
for i in range(len(unfilled_markers_list_1)):
	plt.plot(x[i],y[i], markersize=12, marker=unfilled_markers_list_1[i])
x = np.random.rand(len(unfilled_markers_list_2))
y = np.random.rand(len(unfilled_markers_list_2))
for i in range(len(unfilled_markers_list_2)):
	plt.plot(x[i],y[i],  markersize=12, marker=unfilled_markers_list_2[i])
plt.show()

filled_markers_list = ['.','o','v','^','<','>','8','s','p','*','h','H','D','d','P','X']
x = np.random.rand(len(filled_markers_list))
y = np.random.rand(len(filled_markers_list))
for i in range(len(filled_markers_list)):
	plt.plot(x[i],y[i],  markersize=12, marker=filled_markers_list[i])
plt.show()

在这里插入图片描述
在这里插入图片描述

画3D图

import numpy as np
from matplotlib import pyplot as plt
# #方法一,利用关键字定义坐标轴 
fig = plt.figure()
ax1 = plt.axes(projection='3d')
# ``fig.add_subplot(235)`` is the same as
# ``fig.add_subplot(2, 3, 5)``. Note that this can only be used if there are no more than 9 subplots.
#ax = fig.add_subplot(211,projection='3d')  #这种方法也可以画多个子图
z = np.linspace(0,13,1000)
x = 5*np.sin(z)
y = 5*np.cos(z)
zd = 13*np.random.random(100)
xd = 5*np.sin(zd)
yd = 5*np.cos(zd)
ax1.scatter3D(xd,yd,zd, c = 'red',label='scatter')  #绘制散点图
ax1.plot3D(x,y,z,'gray',label ='plot')    #绘制空间曲线
# 设置标签的大小
ax1.set_xlabel('x', fontsize=12)
ax1.set_ylabel('y', fontsize=12)
ax1.set_zlabel('z', fontsize=12)
# ax1.set_xlim(left = -10, right = 10)
ax1.set_xbound(lower = -10, upper = 10)

# 设置轴刻度 ,matplotlib将刻度放在对应范围的哪个位置,默认情况下这些刻度就是刻度标签;
ax1.set_xticks(np.linspace(-10, 10, 20))
ax1.legend()
plt.show()

在这里插入图片描述

#方法二,利用三维轴方法
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(projection='3d')
x=np.arange(-8,8,0.25)     
y=np.arange(-8,8,0.25)
x,y=np.meshgrid(x,y)   
r=np.sqrt(x**2+y**2)
z=np.sin(r)/r               
ax.plot_surface(x,y,z,rstride=1,cstride=1,label='plot_surface')
ax.contourf(x,y,z,zdir='z')
# ax.contourf(x,y,z)
# 下面两种形式是一样的
# ax.set(xlabel='X', ylabel='Y', zlabel='Z')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('title')
# 下面两个效果是一样的,设置 X 轴的上下限
# ax.set_xlim(left = -10, right = 10)
ax.set_xbound(lower = -10, upper = 10)
# 设置 YZ 轴的上下限
# ax.set_ybound(bottom = 0, top = 1)
# ax.set_zbound(bottom = 0, top = 1)

# 设置轴刻度 ,matplotlib将刻度放在对应范围的哪个位置,默认情况下这些刻度就是刻度标签;
ax.set_xticks(np.linspace(-10, 10, 20))
# 可以将任何其他类型的值作为标签,可以赋值给之前已经设置过的set_xtick。
# ax.set_xticklabels()
# ax.legend()
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np

ax = plt.figure().add_subplot(projection='3d')
# Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x, y)')
# Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
    c_list.extend([c] * 20)
# By using zdir='y', the y value of these points is fixed to the zs value 0
# and the (x, y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x, z)')
# Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Customize the view angle so it's easier to see that the scatter points lie
# on the plane y=0
ax.view_init(elev=20., azim=-35, roll=0)
plt.show()

在这里插入图片描述


http://www.kler.cn/a/457661.html

相关文章:

  • 云效流水线使用Node构建部署前端web项目
  • 【机器学习】 卷积神经网络 (CNN)
  • golang 编程规范 - 项目目录结构
  • 单元测试3.0+ @RunWith(JMockit.class)+mock+injectable+Expectations
  • 拟声 0.60.0 | 拟态风格音乐播放器,支持B站音乐免费播放
  • 《解密奖励函数:引导智能体走向最优策略》
  • driftingblues6_vh靶机
  • 开源 AI 智能名片商城小程序:个人 IP 运营赋能商业腾飞
  • 计算机网络:TCP/IP网络协议
  • 【代码随想录|完全背包问题】
  • interceptor 和异常全局处理 Advice Advice中没有捕获异常
  • 【Linux】:Linux网络编程基础
  • 【学生管理系统】权限管理之角色管理
  • js的讲解
  • JSON结构快捷转XML结构API集成指南
  • 分布式版本管理工具——Git关联远程仓库(github+gitee)
  • Junit如何禁用指定测试类,及使用场景
  • 基于Springboot + vue实现的火锅店管理系统
  • 从基础到实践:一站式RPC技术深入解析
  • Linux下PostgreSQL-12.0安装部署详细步骤
  • 概率统计与随机过程--作业9
  • 【AIGC-ChatGPT职业提示词指令】职业发展的航海指南:在人生的十字路口做出明智抉择
  • 地理坐标系和投影坐标系
  • Rtsplive-视频流-Linux部署
  • Java - 日志体系_Simple Logging Facade for Java (SLF4J)日志门面_SLF4J集成Log4j1.x 及 原理分析
  • 【从零开始入门unity游戏开发之——C#篇34】C#匿名函数(delegate )和Lambda表达式