文章目录
- (待解决)PyCharm中调用远程Python解释器显示Matplotlib绘图
- 遇到的问题
- Matplotlib概览
- 绘图时两种生成坐标系的推荐代码
- python codes of LearnProject
- Matplotlib绘图时显示中文
- Matplotlib Figures 保存
- Matplotlib绘图QA
- ChatGPT 辅助绘图
- Matplotlib绘图的两种模式“block”和“interactive”
- 给子图编序号, 在图中加文字标记
- 图例 legend, 如何让两个标记共用同一个图例标签
- 画累积分布图 with Matplotlib in Python
- 画箱线图 with Matplotlib in Python
- 画直方图, 把纵轴由概率密度改为概率
- 画折线
- 画柱形图条形图, 显示百分比
- Matplotlib 绘图时与LaTeX联用显示公式
- 刻度标签采用科学记数法×10的n次方
- 有两个 y 轴, 如何对齐它们 at y=0 ?
- 有两个 y 轴, 如何设置左边y轴的spine的颜色?
- 坐标轴的左下角(0.,0.)与图的左下角对齐
- 给定 y 值, 从曲线中索引出相应的 x 值
- 绘制多条曲线时,自动分配不同的颜色
- TclError: no display name and no $DISPLAY environment variable
- 二级标题
- 待补充
- 分割线
- 分割线
(待解决)PyCharm中调用远程Python解释器显示Matplotlib绘图
关于matplotlib的后端(Backend)_GG的专栏-CSDN博客 20180915
matplotlib绘图进阶_皮皮blog-CSDN博客 20140714
PyCharm使用远程Python解释器并用matplotlib绘图的方法 - 简书 20171120
远程服务器的GUI显示到本地及Pycharm配置 - 简书 20180929
pycharm 远程显示 matplotlib - 简书 20190303
遇到的问题
问题UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
问题描述: 在使用pycocotools接口时,使用matplotlib显示图片出现了以下问题:
import numpy as np
from PIL import Image
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from pycocotools.coco import COCO
path_to_fruits = "fruits.jpg"
img_fruits = mpimg.imread(path_to_fruits)
plt.imshow(img_fruits)
plt.show()
E:\OtherProgramFiles\Anaconda3\envs\my_gpu_py3\python.exe E:/WorkSpace/Dataset/MyCondaProject004_pycocotools/cy_learn_coco.py
E:/WorkSpace/Dataset/MyCondaProject004_pycocotools/cy_learn_coco.py:31: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
plt.show()
Process finished with exit code 0
原因分析与解决方案:经排查,将上述程序段的from pycocotools.coco import COCO
注释掉就不会报错,后来发现这是由于安装的pycocotools中E:/OtherProgramFiles/Anaconda3/envs/my_gpu_py3/lib/site-packages/pycocotools/coco.py脚本文件中有这么一句; matplotlib.use('Agg')
, 将该句注释掉即可正常显示图片啦。
Matplotlib概览
类比人类和 Matplotlib 画图过程
- | - | - |
---|---|---|
人类 | 画板 | 调色板 |
Matplotlib | FigureCanvas | Renderer |
Matplotlib中的基础类和容器类
Matplotlib 总体来说,它包含两类元素:
- 基础 (primitives) 类:线 (line), 点 (marker), 文字 (text), 图例 (legend), 网格 (grid), 标题 (title), 图片 (image)等;
- 容器 (containers) 类:图 (figure), 坐标系 (axes), 坐标轴 (axis) 和刻度 (tick)[刻度包含刻度本身和刻度标签];
我们可以在四个容器元素上面添加各种基础元素,比如:
- 在图中添加文字、图例、图片、折线;
- 在坐标系中添加线、点、网格、图例和文字;
- 在坐标轴上添加坐标轴标签;
- 在刻度上添加刻度标签以及设置刻度位置点、刻度线、刻度标签位置、主刻度;
the components of a Matplotlib figure
Tutorials — Matplotlib 3.3.2 documentation | Introductory | Usage Guide
画图的四大常见目的/图表可展示的四大关系
- 分布(distribution) 直方图(historgram chart)
- 联系(relationship) 散点图(scatter chart)
- 比较(comparision) 折线图(line chart)
- 构成(composition) 饼状图(pie chart)
散点图 (scatter chart) 用两组数据构成多个坐标点,考察坐标点的分布,判断两变量之间是否存在某种联系的分布模式。
饼状图 (pie chart) 是一个划分为几个扇形的圆形统计图表,用于描述量、频率或百分比之间的相对关系。
Matplotlib颜色表
设定mask的颜色darkorange:'#FF8C00':(255,140,0);
设定point的颜色
blue:'#0000FF':(0,0,255);
green:'#008000':(0,128,0);
purple:'#800080':(128,0,128);
black:'#000000':(0,0,0);
white:'#FFFFFF':(255,255,255);
lime:'#00FF00':(0,255,0);
yellow:'#FFFF00':(255,255,0);
cyan:'#00FFFF':(255,255,0);
red:'#FF0000':(0,0,255);
- matplotlib颜色表 - FINTHON 20181007
- matplotlib颜色设置及Matplotlib颜色对照表 - 知乎 20190510
- Color Hex Color Codes
Color-hex gives information about colors including color models (RGB,HSL,HSV and CMYK), Triadic colors, monochromatic colors and analogous colors calculated in color page. Color-hex.com also generates a simple css code for the selected color. Html element samples are also shown below the color detail page. Simply type the 6 digit color code in the box above and hit enter.
RGB颜色值与十六进制颜色码转换工具
Matplotlib绘制线条时linestyle, marker,color等参数的可选值
- Python里matplotlib的颜色及线条等控制(linestyle/marker/color,全) - 简书 20181025
- matplotlib.legend — Matplotlib 3.4.2 documentation
- Linestyles — Matplotlib 3.1.0 documentation
- matplotlib.markers — Matplotlib 3.7.1 documentation
绘图时两种生成坐标系的推荐代码
使用 plt.rcParams
命令可以查看图的所有默认属性。
推荐方法1:同时生成图和坐标系
推荐方法1:同时生成图和坐标系
fig, ax = plt.subplots() # 默认得到的axes是一个1×1的对象
ax.set(xticks=[], yticks=[])
# tmp_x = range(0, 6)
# tmp_y = np.array([1.1, 1.5, 1.4, 1.5, 1.6, 1.8])
# ax.plot(tmp_x, tmp_y)
ax.text(0.5, 0.5, 'Style 1\n\nfig, ax = plt.subplots()\nax.plot()', ha='center', va='center', size=16, alpha=.5)
plt.show()
fig, axes = plt.subplots(nrows=2, ncols=2) # 得到的axes是一个2×2的对象
for i, ax in enumerate(axes.flat):
ax.set(xticks=[], yticks=[])
s = 'Style 1\n\n' + 'subplot(2,2,' + str(i) + ')'
ax.text(0.5, 0.5, s, ha='center', va='center', size=16, alpha=.5)
plt.tight_layout()
plt.show()
推荐方法2:先生成图,再添加坐标系
fig = plt.figure() # 生成图 (figure)
ax = fig.add_subplot(1, 1, 1) # 添加坐标系 (axes); 子图是坐标系的特例
tmp_x = range(0, 6)
tmp_y = np.array([1.1, 1.5, 1.4, 1.5, 1.6, 1.8])
ax.plot(tmp_x, tmp_y)
# ax.set(xticks=[], yticks=[])
s = 'Style 2\n\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.plot()'
ax.text(0.5, 0.5, s, ha='center', va='center', size=16, alpha=.5, transform=ax.transAxes)
plt.show()
其它方法
其它方法1:生成图 (figure)
plt.figure() # 生成图 (figure)
plt.text(0.5, 0.5, 'Style other1\n\nplt.figure()', ha='center', va='center', size=16, alpha=.5)
plt.xticks([]), plt.yticks([])
plt.show()
其它方法2:直接生成子图
plt.subplot(1, 1, 1) # 直接生成子图
plt.xticks([]), plt.yticks([])
plt.text(0.5, 0.5, 'Style other2\n\nplt.subplot(1, 1, 1)', ha='center', va='center', size=16, alpha=.5)
plt.show()
其它方法3:直接生成坐标系
plt.axes([0.1, 0.1, 0.5, 0.5]) # 直接生成坐标系 plt.axes([l1, b1, w1, h1])
plt.xticks([]), plt.yticks([])
plt.text(0.1, 0.1, 'Style other3\naxes1', ha='left', va='center', size=16, alpha=.5)
plt.axes([0.2, 0.2, 0.5, 0.5])
plt.xticks([]), plt.yticks([])
plt.text(0.1, 0.1, 'Style other3\naxes2', ha='left', va='center', size=16, alpha=.5)
plt.show()
自定义简单模板1
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(3)
tmp_num = 100
tmp_x = range(0, tmp_num)
tmp_y1 = np.random.rand(tmp_num)
tmp_y2 = np.random.rand(tmp_num) * 4
tmp_y3 = np.random.rand(tmp_num) * 2
plt.figure(figsize=(12, 6), dpi=100)
# subplot 1
plt.subplot(3, 1, 1)
plt.plot(tmp_y1, color='b', linewidth=2.0, linestyle='--', label='tmp_y1')
plt.plot([tmp_x[0], tmp_x[-1]], [0.7, 0.7], color='y', linewidth=1.0, linestyle=':', ) # 画一条直线
plt.xlim(-1, len(tmp_x) + 1)
plt.ylim(tmp_y1.min() * 0.8, tmp_y1.max() * 1.2)
_x_tick = range(0, len(tmp_x), 10)
_x_label = ["{}th a".format(i) for i in _x_tick]
plt.xticks(_x_tick, _x_label, rotation=90) # 调整x轴刻度
plt.xlabel('tmp_x')
plt.ylabel('tmp_y1')
plt.legend(loc='upper left', frameon=True) # 显示图例; 图例名称由plt.plot()中的参数label设置;
# subplot 2
plt.subplot(3, 1, 2)
plt.scatter(tmp_x, tmp_y2, c='y', marker='*', alpha=0.5, label='tmp_y2')
plt.xlim(-1, len(tmp_x) + 1)
plt.ylim(tmp_y2.min() * 0.8, tmp_y2.max() * 1.2)
_x_tick = range(0, len(tmp_x), 10)
_x_label = ["{}th a".format(i) for i in _x_tick]
plt.xticks(_x_tick, _x_label, rotation=90)
plt.xlabel('tmp_x')
plt.ylabel('tmp_y2')
plt.legend(loc='upper right', frameon=True)
# subplot 2
plt.subplot(3, 1, 3)
plt.scatter(tmp_x, tmp_y3, c='b', marker='+', alpha=0.5, label='tmp_y3')
plt.xlim(-1, len(tmp_x) + 1)
plt.ylim(tmp_y3.min() * 0.8, tmp_y3.max() * 1.2)
_x_tick = range(0, len(tmp_x), 10)
_x_label = ["{}th a".format(i) for i in _x_tick]
plt.xticks(_x_tick, _x_label, rotation=90)
plt.xlabel('tmp_x')
plt.ylabel('tmp_y3')
plt.legend(loc='upper right', frameon=True)
# plt.grid(True) # 显示网格线
plt.tight_layout()
plt.show()
# print(plt.rcParams)
python codes of LearnProject
Matplotlib.pdf | 1.1 概览
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# matplotlib inline 就是在 Jupyter Notebook 里面内嵌画图的
# flag_1 = True
flag_1 = False
if flag_1:
# Matplotlib.pdf | 1.1 概览
tmp_fig = plt.figure() # 图 (figure)
tmp_axes = tmp_fig.add_subplot(1, 1, 1) # 坐标系 (axes); 子图是坐标系的特例
plt.show()
tmp_x_axis = tmp_axes.xaxis # 坐标轴 (axis)
tmp_y_axis = tmp_axes.yaxis
print('tmp_fig.axes:', tmp_fig.axes, '\n')
print('tmp_axes.xaxis:', tmp_x_axis)
print('tmp_axes.yaxis:', tmp_y_axis, '\n')
print('tmp_axes.xaxis.majorTicks:', tmp_x_axis.majorTicks) # 刻度 (tick)
print('tmp_axes.yaxis.majorTicks:', tmp_y_axis.majorTicks, '\n')
print('tmp_axes.xaxis.minorTicks:', tmp_x_axis.minorTicks)
print('tmp_axes.yaxis.minorTicks:', tmp_y_axis.minorTicks, '\n')
# 由坐标系和坐标轴指向同一个图 (侧面验证了图、坐标系和坐标轴的层级性)
print('tmp_axes.figure:', tmp_axes.figure)
print('tmp_x_axis.figure:', tmp_x_axis.figure)
print('tmp_y_axis.figure:', tmp_y_axis.figure)
# flag_2 = True
flag_2 = False
if flag_2:
# Matplotlib.pdf | 1.5 刻度 | 刻度展示
tmp_fig = plt.figure()
tmp_axes = tmp_fig.add_subplot(1, 1, 1)
tmp_axes.set_xlim(10**3, 10**10)
tmp_axes.set_xscale('log')
# 设置numticks=15时, 这里显示了8个刻度; 如果设置的numticks少于实际所需的刻度数目, 例如设置成6时, 则这里只会显示5个刻度;
tmp_axes.xaxis.set_major_locator(ticker.LogLocator(base=10.0, numticks=15))
tmp_axes.text(0.0, 0.1, "LogLocator(base=10.0, numticks=15)", fontsize=14, transform=tmp_axes.transAxes)
# tmp_axes.patch.set_color('black')
# tmp_axes.patch.set_alpha(0.15)
plt.show()
Matplotlib.pdf | 3.1 概览
# Matplotlib.pdf | 3.1 概览
from yahoofinancials import YahooFinancials
import pandas as pd
def data_converter(price_data, code, asset):
# convert raw data to dataframe
if asset == 'FX':
code = str(code[3:] if code[:3]=='USD' else code) + '=X'
columns = ['open', 'close', 'low', 'high']
price_dict = price_data[code]['prices']
index = [p['formatted_date'] for p in price_dict] # 用列表解析式将日期获取出来
price = [[p[c] for c in columns] for p in price_dict] # 用列表解析式将价格获取出来
data = pd.DataFrame(price, index=pd.Index(index, name='date'), columns=pd.Index(columns, name='OHLC'))
return data
start_date = '2018-04-29'
end_date = '2019-04-29'
stock_code = ['NVDA', 'AMZN', 'BABA', 'FB', 'AAPL'] # 股票
currency_code = ['EURUSD=X', 'JPY=X', 'CNY=X'] # 汇率
stock = YahooFinancials(stock_code)
currency = YahooFinancials(currency_code)
stock_daily = stock.get_historical_price_data(start_date, end_date, 'daily')
currency_daily = currency.get_historical_price_data(start_date, end_date, 'daily')
# print('stock_daily的值\n', stock_daily, '\n')
# print('currency_daily的值\n', currency_daily, '\n')
NVDA = data_converter(stock_daily, 'NVDA', 'EQ')
print('NVDA.head(3).append(NVDA.tail(3))的值\n',NVDA.head(3).append(NVDA.tail(3)), '\n')
EURUSD = data_converter(currency_daily, 'EURUSD', 'FX')
print('EURUSD.head(3).append(EURUSD.tail(3))的值\n', EURUSD.head(3).append(EURUSD.tail(3)), '\n')
Matplotlib绘图时显示中文
方法一(报错了):通过使用字体管理器font_manager
方法一(报错了):通过使用字体管理器font_manager
from matplotlib import font_manager # 导入字体管理器
my_font = font_manager.FontProperties(fname=r"C:\Windows\Fonts\MSYHBD.ttc", size=15) # 微软雅黑
E:\OtherProgramFiles\Anaconda3\envs\my_gpu_py3\lib\site-packages\matplotlib\backends\backend_agg.py:238: RuntimeWarning: Glyph 26102 missing from current font.
font.set_text(s, 0.0, flags=flags)
方法二:通过在代码中动态设置中文字体
方法二:通过在代码中动态设置中文字体
import pylab
# 设置汉字格式; sans-serif就是无衬线字体, 是一种通用字体族;
# 常见的无衬线字体有 Trebuchet MS, Tahoma, Verdana, Arial, Helvetica, SimHei, 中文的幼圆, 隶书等等;
pylab.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
pylab.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
Matplotlib Figures 保存
tikzplotlib · PyPI
This is tikzplotlib, a Python tool for converting matplotlib figures into PGFPlots (PGF/TikZ) figures like for native inclusion into LaTeX or ConTeXt documents.
Matplotlib绘图QA
ChatGPT 辅助绘图
-
xxx
-
Q:x=np.arange(0, 100, 6), y=np.random.rand(17),用 Matplotlib 帮我绘制高级美观的散点图,要求能对第三个点设置不同的颜色,并给第五个点加一条柱状线。
帮我优化代码,以便能够自定义设置点的大小,柱状线的线性。
帮我优化代码,以便标记出第三个点的坐标,并支持自定义设置横纵坐标轴刻度间隔,包括 Major tick 和 Minor tick 以及 label。 -
xxx
-
Q:给定一个用一维数组表示的数值序列,如何用 Python 代码实现找出该序列的所有局部最小值和最大值?
-
xxx
-
Q:请给我提供一份可用于paper的绘制散点图的Python代码,要求散点图的风格符合学术科研文献的规范。
请修改上述代码以便支持自定义画布的figsize和dpi。
请修改上述代码以便让x轴的0刻度线向右偏移一点而与y轴保持一定的距离。 -
Q:请问在Matplotlib中,ax.axhline()的用法,如何设置颜色和线宽?
请问在Matplotlib中,ax.axhline()函数还有哪些参数可以使用? -
xxx
-
Q:plt.subplots有多个图时,如何逐个图设置坐标轴的Major tick 和 Minor tick?
plt.subplots有多个图时,如何逐个图设置坐标轴刻度的字体大小?
plt.subplots有多个图时,如何逐个图设置坐标轴刻度的位置?
plt.subplots有多个图时,如何逐个图设置图例的大小、marker的大小、网格线?
plt.subplots有多个图时,如何逐个图设置图例的边框颜色和透明度?
plt.subplots有多个图时,如何逐个图设置y轴的刻度颜色?
plt.subplots有多个图时,如何逐个图设置y轴的spines颜色? -
xxx
Matplotlib绘图的两种模式“block”和“interactive”
matplotlib绘图的两种模式“block”和“interactive” - 简书 20180927
block模式特点:
(1)plt.polt()
等绘图函数不会直接在窗口中绘图,只有调用plt.show()
(窗口不会自动关闭)或plt.pause()
(窗口自动关闭)时才将内存中的图绘制到窗口;
(2)程序碰到第一个plt.show()
时,绘图后会暂停执行,直到手动关闭当前窗口才继续执行后面的代码,这就是“阻塞”的含义;
(3)plt.pause(time)
函数也能实现窗口绘图(不需要plt.show
),但窗口只停留 time 时间便会自动关闭,然后再继续执行后面代码;plt.pause()
会把它之前的所有绘图都绘制在对应坐标系中,而不仅仅是在当前坐标系中绘图;特别要注意的是,plt.pasue(0)
将绘制之前的所有图像,且图像窗口不会自动关闭,但程序会停止在该语句所在位置,即使手动关闭窗口也不会继续执行后面的代码;
(4)如果plt.pause()
和plt.show()
一起使用时,前者相当于只是暂停时间,而在窗口中绘图的工作将由plt.show()
完成,因此后者的总用占主要位置;
(5)在Python脚本中默认是block模式的。
interactive模式特点:
(1)开启interactive模式,用plt.ion()
,放在绘图之前,关闭该模式用plt.ioff()
;
(2)不用plt.show()
或plt.pause()
,只要plt.plot()
等语句就能在窗口中绘图,但是,绘图后窗口立马自动关闭,你压根都没法看清楚;可以用plt.pause(time)
进行延迟自动关闭时间,需要注意的是如果有多个plt.pause()
穿插在不同绘图函数下,那么前面的窗口不会先关闭,会等到最后一个plt.pause()
结束后再一起关闭。该模式下要实现同时绘图,且保持,可用plt.pause(0)
,但程序会结束在该位置,手动关闭窗口也不会继续执行了,因此plt.pause(0)
应放在程序最后。
(3)该模式下,即使用了plt.show()
也依然会自动关闭窗口,可在调用plt.show()
之前调用plt.ioff()
关闭交互模式,恢复到阻塞模式。
(4)iPython环境下默认是interactive模式。
给子图编序号, 在图中加文字标记
- Q:请问Matplotlib中,如何在每个subplot的底部居中位置添加(a),(b),©等字母序号和文字说明,麻烦给出代码示例
Labelling subplots — Matplotlib 3.8.1 documentation - Q:xxx
图例 legend, 如何让两个标记共用同一个图例标签
20231105记:
在画折线图时,画了四条折线,a折线是采用方点表示数据点的实线折线,b折线是采用方点表示数据点的虚线折线,c折线是采用圆点表示数据点的实线折线,d折线是采用圆点表示数据点的虚线折线,在生成图例时,希望a折线和c折线共用一个标明实线含义的标签,希望b折线和d折线共用一个标明虚线含义的标签。简单来说,就是如何让两个标记共用同一个图例标签?
谷歌检索"matplotlib legend line marker separately",
- (待阅读) python - How to make two markers share the same label in the legend - Stack Overflow
- (待阅读) python - Handle legend markers independently - Stack Overflow
画累积分布图 with Matplotlib in Python
画箱线图 with Matplotlib in Python
画直方图, 把纵轴由概率密度改为概率
20230412记:把直方图的纵轴由概率密度改为概率;
谷歌检索"python plt.hist probability display",必应检索"python 直方图 频率";
谷歌检索"Matplotlib histogram probability"“Matplotlib bins probability”“sns.histplot bins”;
- *** python - Plot a histogram such that bar heights sum to 1 (probability) - Stack Overflow 20230407
- matplotlib.pyplot.hist — Matplotlib 3.7.1 documentation
- About histogram plot in matplotlib in Python - Stack Overflow 20221030
20230412记:plt.hist
的返回值的含义:
import matplotlib.pyplot as plt
data = [8, 8, 9, 12, 13, 13, 14, 14, 15, 18, 22, 23, 24, 25, 30]
plt.figure(figsize=(8,8))
plt.subplot(221)
tmp1 = plt.hist(data, bins=4, edgecolor='black')
plt.subplot(222)
tmp2 = plt.hist(data, bins=4, density=True, edgecolor='black')
# tmp1[0]/(sum(tmp1[0])*np.diff(tmp1[1])) 的值与 tmp2[0] 的值相等
>>> tmp1
(array([6., 4., 3., 2.]), array([ 8. , 13.5, 19. , 24.5, 30. ]), <BarContainer object of 4 artists>)
>>> tmp2
(array([0.07272727, 0.04848485, 0.03636364, 0.02424242]), array([ 8. , 13.5, 19. , 24.5, 30. ]), <BarContainer object of 4 artists>)
>>> import numpy as np
>>> tmp1[0]/(sum(tmp1[0])*np.diff(tmp1[1]))
array([0.07272727, 0.04848485, 0.03636364, 0.02424242])
import seaborn as sns
plt.subplot(223)
sns.histplot(data=data, stat='probability', bins=[8, 13.5, 19, 24.5])
plt.subplot(224)
sns.histplot(data=data, stat='probability', bins=[8, 13.5, 19, 24.5, 30])
plt.show()
画折线
- Q:我需要对四组实验的三个性能指标进行对比分析,这三个性能指标具有不同的量纲,请给我提供一份可用于paper的绘制折线的Python代码,要求折线图的风格符合学术科研文献的规范,折线图能有三个分别指示各个性能指标的y轴刻度。
请修改上述代码以便支持同时对四组实验的三个性能指标进行对比分析。 - Q:xxx
画柱形图条形图, 显示百分比
20231104记:Draw the percentage bar graph
- Q:我需要对不同年龄段的男生、女生的近视情况进行对比分析,请给我提供一份可用于paper的绘制条形图的Python代码,要求条形图的风格符合学术科研文献的规范。
- sns.histplot(data=residual, stat=‘proportion’, bins=residual_bins)
- Percentage Bar Graph| Definition, How To Draw & Solved Examples! 20230517
- Visualizing distributions of data — seaborn 0.13.0 documentation
- python - How to display percentage above grouped bar chart - Stack Overflow
- Grouped bar chart with labels — Matplotlib 3.8.2 documentation
Matplotlib 绘图时与LaTeX联用显示公式
20231104记:Matplotlib绘图加文字时如何添加公式以及叉乘、摄氏度等符号,
- python - How do I print a Celsius symbol with matplotlib? - Stack Overflow 20111211
- matplotlib - Superscript in Python plots - Stack Overflow 20140120
- math mode - What is the LaTeX code to put a multiplication symbol into a matplotlib title? - TeX - LaTeX Stack Exchange 20150427
刻度标签采用科学记数法×10的n次方
20231203记:
- Matplotlib刻度标签采用科学记数法×10的n次方_-CSDN博客 20230430
- python matplotlib 作图 ,xlabel位置和坐标刻度字体大小如何设置? - lne的科研记录本的回答 - 知乎 20230806
有两个 y 轴, 如何对齐它们 at y=0 ?
问题描述:
有两个 y 轴, 如何对齐它们 at y=0 ?
原因分析and解决方案:
暂未亲测;
有两个 y 轴, 如何设置左边y轴的spine的颜色?
问题描述:
import matplotlib.pyplot as plt
plt.style.use('default')
# 创建一个子图
fig, axes = plt.subplots(1, 1)
# 在子图中绘制图形
axes.plot([1, 2, 3], [1, 2, 3])
# 设置左边 y 轴的 spines 颜色为绿色
axes.spines['left'].set_color('green')
# 创建一个 twinx 坐标轴对象
ax1_twin = axes.twinx()
# 设置右边 y 轴的 spines 颜色为紫色
ax1_twin.spines['right'].set_color('#B177DE')
plt.show()
20231203 15:35记:上述代码示例中,左边 y 轴的 spine 颜色为什么显示出来是黑色的?为什么在这个示例代码中无法设置左边y轴的spine的颜色为绿色?
原因分析and解决方案:
20240128 20:05记:上述代码示例中,左边 y 轴的 spine 颜色之所以显示出来是黑色的,是因为在显示时ax1_twin.spines覆盖了axes.spines,导致左边 y 轴显示的是ax1_twin.spines的左 spine 颜色。修改上述代码示例,删除这行代码axes.spines['left'].set_color('green')
,加上这行代码ax1_twin.spines['left'].set_color('green')
,便可设置左边y轴的spine的颜色为绿色。
坐标轴的左下角(0.,0.)与图的左下角对齐
问题描述:
坐标轴的左下角(0.,0.)与图的左下角对齐;
原因分析and解决方案:
The axis
function in the example plt.axis([0, 6, 0, 20])
takes a list of [xmin, xmax, ymin, ymax]
and specifies the viewport of the axes.
给定 y 值, 从曲线中索引出相应的 x 值
问题描述:
给定 y 值, 从曲线中索引出相应的 x 值;
原因分析and解决方案:
use the interp function from numpy library,
import numpy as np
x = [0.01474926, 0.96923077, 1]
y = [1, 0.7875, 0]
np.interp(0.75, x,y)
0.8363082148652623
绘制多条曲线时,自动分配不同的颜色
问题描述:
20230326记:绘制多条曲线时,Matplotlib会自动为不同的曲线分配不同的颜色,那么如何手动地调出下一条曲线的颜色呢?
解决方案:
例如,
df = pd.read_csv('data.csv')
plt_tmp = df.plot(**kwargs) # 这里, `plt_tmp`为一个`matplotlib.axes.Axes`实例;
plt.scatter(x, y, c=next(plt_tmp.axes._get_lines.prop_cycler)['color'], marker="o", label='y1')
Styling with cycler — Matplotlib 3.7.1 documentation
Demo of custom property-cycle settings to control colors and other style properties for multi-line plots.
自定义属性周期设置,可以控制多线图的颜色和其他样式属性。
matplotlib.axes.Axes.set_prop_cycle — Matplotlib 3.7.1 documentation
Axes.set_prop_cycle(*args, **kwargs)
Set the property cycle of the Axes.
The property cycle controls the style properties such as color, marker and linestyle of future plot commands. The style properties of data already added to the Axes are not modified.
matplotlib.axes.Axes.plot — Matplotlib 3.7.1 documentation
By default, each line is assigned a different style specified by a ‘style cycle’.
Alternatively, you can also change the style cycle usingrcParams["axes.prop_cycle"]
(default:cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])
).
TclError: no display name and no $DISPLAY environment variable
问题描述:
20230327记:在远程服务器上通过 Matplotlib 画图时报错:_tkinter.TclError: no display name and no $DISPLAY environment variable
。
原因分析and解决方案:
- How to fix “_tkinter.TclError: no display name and no $DISPLAY environment variable” error – Its Linux FOSS
- 【matplotlib】 之 _tkinter.TclError: no display name and no $DISPLAY environment variable_tz_zs的博客-CSDN博客 20180911
二级标题
待补充
待补充
数学公式粗体
\textbf{}
或者
m
e
m
o
r
y
{\bf memory}
memory
数学公式粗斜体
\bm{}
摘录自“bookname_author”
此文系转载,原文链接:名称 20200505
高亮颜色说明:突出重点
个人觉得,:待核准个人观点是否有误
分割线
分割线
我是颜色为00ffff的字体
我是字号为2的字体
我是颜色为00ffff, 字号为2的字体
我是字体类型为微软雅黑, 颜色为00ffff, 字号为2的字体
分割线
分割线
问题描述:
原因分析:
解决方案: