我正在尝试用seaborn绘制热图并将其导出到pgf,以便在Latex中轻松导入.这或多或少都有效,唯一困扰我的是颜色条被导出为额外的png.
因此,如果我将导出运行到pgf,我会得到以下结果:
test.pgf
测试img0.png
这绝对是不合需要的,因为png不能很好地缩放.一些MWE:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame.from_csv("test.csv", sep=',')
sns.set('paper', 'white', rc={'font.size': 10, 'axes.labelsize': 10, 'legend.fontsize': 8, 'axes.titlesize': 10,
'xtick.labelsize': 8,
'ytick.labelsize': 8, "pgf.rcfonts": False})
plt.rc('font', **{'family': 'serif', 'serif': ['Times']})
plt.rc('text', usetex=True)
fig = plt.figure()
ax = sns.heatmap(df, linewidths=.5)
fig.savefig('test.pdf')
fig.savefig('test.pgf')
和test.csv的内容:
0,1,2,3,4
1,1,1,1,1
2,2,2,2,2
3,3,3,3,3
有没有人有解决方案将颜色条包含在pgf输出中?
1> Daan..:
我发现了导出到pgf/tikz的库中的一些特性.
首先,在中matplotlib
,quadmesh(即热图)正确导出到pgf,但是colorbar导出为png(op遇到的).
我和matplotlib2tikz
库试过同样的事情.在这种情况下,quadmesh将导出为png,但可以正确导出色彩映射.但是,如果禁止热图,例如通过将色彩图绘制为单独的Axes
并清除热图轴,则颜色条将导出为png.
因此,如果将两个导出的输出结合起来,则可以同时使用它们.
热图:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame.from_csv("test.csv", sep=',')
sns.set('paper', 'white',
rc={'font.size': 10, 'axes.labelsize': 10,
'legend.fontsize': 8, 'axes.titlesize': 10,
'xtick.labelsize': 8,'ytick.labelsize': 8,
"pgf.rcfonts": False,
})
plt.rc('font', **{'family': 'serif', 'serif': ['Times']})
plt.rc('text', usetex=True)
fig, ax = plt.subplots(figsize=(6,6))
ax = sns.heatmap(df, linewidths=.5, ax=ax, cbar=False)
fig.savefig('heatmap_nocbar.pgf')
请注意,我禁止使用颜色条绘制 cbar=False
然后获取颜色栏:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from matplotlib2tikz import save as tikz_save
df = pd.DataFrame.from_csv("test.csv", sep=',')
sns.set('paper', 'white',
rc={'font.size': 10, 'axes.labelsize': 10,
'legend.fontsize': 8, 'axes.titlesize': 10,
'xtick.labelsize': 8,'ytick.labelsize': 8,
"pgf.rcfonts": False,
})
plt.rc('font', **{'family': 'serif', 'serif': ['Times']})
plt.rc('text', usetex=True)
fig, ax = plt.subplots()
ax = sns.heatmap(df, linewidths=.5, ax=ax, )
tikz_save('colormap.tex', figure=fig, strict=True)
解决方案现在需要一些肮脏的工作 我知道这不是一个好习惯,但这是我能找到的唯一方法.
在colormap.tex
文件中,您需要删除除色彩图所需的所有行.
开头colormap.tex
:
\begin{tikzpicture}
\begin{axis}[
... % definition of axis: delete these lines
colorbar,
colormap={mymap}{[1pt]
...
所以你得到这个:
\begin{tikzpicture}
\begin{axis}[
hide axis,
colorbar,
colormap={mymap}{[1pt]
...
在文件的末尾,删除方括号的关闭和之间的所有内容\end{axis}
:
]
... %delete these lines
\end{axis}
文件中的这个更改可以自动化,我在github上的代码中包含了一个示例
在主tex文件中,您可以添加这两个数字
\input{heatmap_nocbar.pgf}
\input{colorbar.tex}
如果你想要一个完整的工作示例和完整的输出,我已经把这个答案中的所有内容放在github上.
这可能远非一个完美的答案,但我缺乏python技能深入了解后端matplotlib
并matplotlib2tikz
给出一个更好的例子.