matplotlib - Omics - Hunter https://evvail.com Evvail | 一个经验分享的地方 Tue, 19 Jan 2021 02:13:24 +0000 zh-CN hourly 1 https://evvail.com/wp-content/uploads/2019/08/cropped-1-32x32.jpg matplotlib - Omics - Hunter https://evvail.com 32 32 python – 给图片添加水印 https://evvail.com/2021/01/17/2157.html https://evvail.com/2021/01/17/2157.html#respond Sun, 17 Jan 2021 15:05:04 +0000 https://evvail.com/?p=2157 在python里面给图片添加水印的方法有很多,诸如PIL、matp...

The post python – 给图片添加水印 first appeared on Omics - Hunter.

]]>
在python里面给图片添加水印的方法有很多,诸如PIL、matplotlib等包都可以快速给图片添加文字或者图片水印。本文主要介绍如何利用matplotlib给图片快速添加文字水印,例子如下:


# 加载必备包
import numpy as np
import matplotlib.pyplot as plt


np.random.seed(2021)
fig, ax = plt.subplots()

# 绘制点图
ax.plot(np.sin(10 * np.linspace(0, 1)), '-o', ms=20, alpha=0.7, mfc='orange')
# 添加网格
ax.grid()
# 添加文字水印,参考https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.text.html
fig.text(0.9, 0.1,               # 文字相对位置,(0,0)是左下角,而(1,1)是右上角
         'Watermark@copyright',  # 文字内容
         fontsize=30,            # 文字大小
         color='gray',           # 字体颜色
         ha='right', va='bottom',# 垂直、水平位置
         alpha=0.2,              # 水印透明度
         rotation=30             # 文字旋转角度
        )
# 绘图
plt.show()

也可以用fig.figimage添加图片水印,更多内容可以参考matplotlib官方文档。

参考资料:

1.https://matplotlib.org/gallery/images_contours_and_fields/watermark_image.html

2.https://matplotlib.org/gallery/text_labels_and_annotations/watermark_text.html

The post python – 给图片添加水印 first appeared on Omics - Hunter.

]]>
https://evvail.com/2021/01/17/2157.html/feed 0
Python 用matplotlib绘制小提琴图 https://evvail.com/2020/12/29/2115.html https://evvail.com/2020/12/29/2115.html#respond Tue, 29 Dec 2020 15:48:13 +0000 https://evvail.com/?p=2115 小提琴图是常用的数据数据可视化方式。用matplotlib绘制小提...

The post Python 用matplotlib绘制小提琴图 first appeared on Omics - Hunter.

]]>
小提琴图是常用的数据数据可视化方式。用matplotlib绘制小提琴图也是很便捷的,同时也可以添加完整的箱线图。(为什么写这一篇文章呢?有朋友说matplotlib绘制的小提琴不能添加完整的箱线图,虽然用seaborn也是一个比较好的选择,但是matplotlib作为基础包还是有必要深挖的。只要你想添加,matplotlib也是可以添加完整的箱线图)

下面借用官网示例给大家演示小提琴的绘制过程:


import matplotlib.pyplot as plt
import numpy as np

# 计算分位数
def adjacent_values(vals, q1, q3):
    upper_adjacent_value = q3 + (q3 - q1) * 1.5
    upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])

    lower_adjacent_value = q1 - (q3 - q1) * 1.5
    lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
    return lower_adjacent_value, upper_adjacent_value

# 坐标轴样式
def set_axis_style(ax, labels):
    ax.get_xaxis().set_tick_params(direction='out')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_xticks(np.arange(1, len(labels) + 1))
    ax.set_xticklabels(labels)
    ax.set_xlim(0.25, len(labels) + 0.75)
    ax.set_xlabel('Sample name')
    
    
# 创建演示数据集
np.random.seed(2020)
data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)]

# 定义画布
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 4))

# 设置标题
ax.set_title('Customized violin plot')

# 绘制小提琴图
parts = ax.violinplot(
        data, showmeans=False, showmedians=False,
        showextrema=False)

# 设置填充颜色和边框颜色
for pc in parts['bodies']:
    pc.set_facecolor('#D43F3A')
    pc.set_edgecolor('black')
    pc.set_alpha(0.5)

# 计算中位数,上四分位和下四分位,绘制小提琴内部盒状图
quartile1, medians, quartile3 = np.percentile(data, [25, 50, 75], axis=1)
whiskers = np.array([
    adjacent_values(sorted_array, q1, q3)
    for sorted_array, q1, q3 in zip(data, quartile1, quartile3)])
whiskers_min, whiskers_max = whiskers[:, 0], whiskers[:, 1]

# 添加点和竖线
inds = np.arange(1, len(medians) + 1)
ax.scatter(inds, medians, marker='o', color='white', s=30, zorder=3)
ax.vlines(inds, quartile1, quartile3, color='k', linestyle='-', lw=5)
ax.vlines(inds, whiskers_min, whiskers_max, color='k', linestyle='-', lw=1)

# 设置坐标轴样式
labels = ['A', 'B', 'C', 'D']
set_axis_style(ax, labels)

plt.subplots_adjust(bottom=0.15, wspace=0.05)
plt.show()

如此一张完整的小提琴就绘制完成了。

参考资料:

1.https://matplotlib.org/gallery/statistics/customized_violin.html#sphx-glr-gallery-statistics-customized-violin-py

The post Python 用matplotlib绘制小提琴图 first appeared on Omics - Hunter.

]]>
https://evvail.com/2020/12/29/2115.html/feed 0
Python 绘制极坐标图 https://evvail.com/2020/12/15/2062.html https://evvail.com/2020/12/15/2062.html#respond Tue, 15 Dec 2020 15:37:56 +0000 https://evvail.com/?p=2062 用Python来绘制极坐标图也是非常简单的,之前文章有提到用《R ...

The post Python 绘制极坐标图 first appeared on Omics - Hunter.

]]>
用Python来绘制极坐标图也是非常简单的,之前文章有提到用《R 绘制极坐标堆积柱状图》,本文主要介绍如何用python可视化神器-matplotlib来绘制极坐标图。


# 加载包,numpy主要生成模拟数据;matplotlib用于绘图
import numpy as np
import matplotlib.pyplot as plt


# 设置随机数
np.random.seed(2020)

# 计算分块大小,数据
N = 20
theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
radii = 10 * np.random.rand(N)
width = np.pi / 4 * np.random.rand(N)
colors = plt.cm.viridis(radii / 10.)

# 设置图片大小
plt.figure(figsize=(8, 8))
# 设置画布排列
ax = plt.subplot(111, projection='polar')
ax.bar(theta, radii, width=width, bottom=1.0, color=colors, alpha=0.5)

# 设置网格线样式
ax.grid(linestyle='-.', alpha=0.3)

# 隐藏网格线
# ax.grid(False)

# 隐藏坐标轴
# plt.axis('off')

plt.show()

如此,是不是也非常方便呢?另外感兴趣的小伙伴可以研究下matplotlib的logo的绘制:官方代码

参考资料:

1.https://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/polar_bar.html#sphx-glr-gallery-pie-and-polar-charts-polar-bar-py

The post Python 绘制极坐标图 first appeared on Omics - Hunter.

]]>
https://evvail.com/2020/12/15/2062.html/feed 0
Python 用matplotlib绘制双坐标图 https://evvail.com/2020/11/05/1820.html https://evvail.com/2020/11/05/1820.html#respond Thu, 05 Nov 2020 15:39:22 +0000 https://evvail.com/?p=1820 双坐标图一般用于我们展示多维数据,常见的方式是共享x轴,左右两边Y...

The post Python 用matplotlib绘制双坐标图 first appeared on Omics - Hunter.

]]>
双坐标图一般用于我们展示多维数据,常见的方式是共享x轴,左右两边Y轴刻度不一样或者按照比例缩放。matplotlib作为python绘图主要工具,绘制双坐标图也非常简单。

此处利用公开的数据集(美国economics数据集)做演示:


import pandas as pd
import matplotlib.pyplot as plt

# 导入数据
df = pd.read_csv("economics.csv")

x = df['date']
y1 = df['psavert']
y2 = df['unemploy']

# 绘制折线图(左Y轴)
fig, ax1 = plt.subplots(1,1,figsize=(16,9), dpi= 80)
ax1.plot(x, y1, color='tab:red')

# 绘制折线图(右Y轴)
ax2 = ax1.twinx()  # 共享X轴
ax2.plot(x, y2, color='tab:blue')

# 坐标轴样式
# 左Y轴
ax1.set_xlabel('Year', fontsize=20) # 设置x轴标签
ax1.tick_params(axis='x', rotation=0, labelsize=12) # 设置刻度
ax1.set_ylabel('Personal Savings Rate', color='tab:red', fontsize=20) # 设置y轴标签
ax1.tick_params(axis='y', rotation=0, labelcolor='tab:red' )
ax1.grid(alpha=.4) # 设置网格参数

# 右Y轴
ax2.set_ylabel("# Unemployed (1000's)", color='tab:blue', fontsize=20)
ax2.tick_params(axis='y', labelcolor='tab:blue')
ax2.set_xticks(np.arange(0, len(x), 60))
ax2.set_xticklabels(x[::60], rotation=90, fontdict={'fontsize':10})
ax2.set_title("Personal Savings Rate vs Unemployed: Plotting in Secondary Y Axis", fontsize=22)
fig.tight_layout()
plt.show()

更多的绘图方法下面参考资料给出了详尽的示例包括代码,建议学习。

参考资料:

1.https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python

The post Python 用matplotlib绘制双坐标图 first appeared on Omics - Hunter.

]]>
https://evvail.com/2020/11/05/1820.html/feed 0
Python数据可视化-matplotlib显妙招 https://evvail.com/2020/05/13/523.html https://evvail.com/2020/05/13/523.html#respond Wed, 13 May 2020 10:55:59 +0000 https://evvail.com/?p=523 matplotlib是基于Python语言的开源项目,旨在为Pyt...

The post Python数据可视化-matplotlib显妙招 first appeared on Omics - Hunter.

]]>
matplotlib是基于Python语言的开源项目,旨在为Python提供一个数据绘图包,是python最主要的可视化工具之一。

本文主要简单给大家介绍如果绘制高大上的组合图(python3环境):


# coding = "utf8"

import numpy as np
import matplotlib.pyplot as plt

# 生成随机数据集
np.random.seed(202005)
x = np.random.randn(1000)
y = np.random.randn(1000)


def scatter_hist(x, y, ax, ax_histx, ax_histy):
    # 去掉侧图标签,刻度等
    ax_histx.tick_params(axis="x",
                         labelleft=False,
                         labelbottom=False,
                         labeltop=False,
                         labelright=False,
                         left=False,
                         bottom=False,
                         top=False,
                         right=False)
    ax_histy.tick_params(axis="y",
                         labelleft=False,
                         labelbottom=False,
                         labeltop=False,
                         labelright=False,
                         left=False,
                         bottom=False,
                         top=False,
                         right=False
                         )

    # 绘制散点图
    ax.scatter(x, y, c="red")

    # 分割区域设置
    binwidth = 0.25
    xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
    lim = (int(xymax/binwidth) + 1) * binwidth
    # 添加侧边柱状图
    bins = np.arange(-lim, lim + binwidth, binwidth)
    ax_histx.hist(x, bins=bins, density=True, histtype="step")
    ax_histy.hist(y, bins=bins, density=True, orientation='horizontal')


if __name__ == "__main__":
    # 定义坐标轴
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    spacing = 0.005

    # 定义画布大小
    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom + height + spacing, width, 0.2]
    rect_histy = [left + width + spacing, bottom, 0.2, height]

    # 创建一个图片
    fig = plt.figure(figsize=(8, 8))
    # 添加散点图区域
    ax = fig.add_axes(rect_scatter)
    # 添加柱状图区域
    ax_histx = fig.add_axes(rect_histx, sharex=ax)
    # 去掉顶部、右边边框
    ax_histx.spines['top'].set_visible(False)
    ax_histx.spines['right'].set_visible(False)
    # 同上
    ax_histy = fig.add_axes(rect_histy, sharey=ax)
    ax_histy.spines['top'].set_visible(False)
    ax_histy.spines['right'].set_visible(False)

    # 绘图
    scatter_hist(x, y, ax, ax_histx, ax_histy)

    plt.show()

一个简单的组合图绘制好了,更多绘图姿势请参考文章。

参考文章:

1.https://matplotlib.org/gallery/index.html

The post Python数据可视化-matplotlib显妙招 first appeared on Omics - Hunter.

]]>
https://evvail.com/2020/05/13/523.html/feed 0