我是matplotlib的新手,不会在Latex中使用图形。 视觉输出为图形,但是:
为什么没有pdf输出?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os #to remove a file
import datetime
from matplotlib.backends.backend_pdf import PdfPages
#######################
Val1 = [1,2,3,4,5,6,7,8,9,9,5,5] # in kWh
Val2 = [159,77,1.716246,2,4,73,128,289,372,347,354,302] #in m³
index = ['Apr', 'Mai', 'Jun', 'Jul','Aug','Sep','Okt','Nov','Dez','Jan', 'Feb', 'Mrz']
df = pd.DataFrame({'Val1': Val1,'Val2': Val2}, index=index)
with PdfPages('aas2s.pdf') as pdf:
plt.rc('text', usetex=True)
params = {'text.latex.preamble' : [r'\usepackage{siunitx}', r'\usepackage{amsmath}']}
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = 'Liberation'
plt.rcParams.update(params)
plt.figure(figsize=(8, 6))
plt.rcParams.update({'font.size': 12})
ax = df[['Val1','Val2']].plot.bar(color=['navy','maroon'])
plt.xlabel('X Achse m')
plt.ylabel('Y Achse Taxi quer ')
plt.legend(loc='upper left', frameon=False)
plt.title('Franz jagt im komplett verwahrlosten Taxi quer durch Bayern')
plt.show()
pdf.savefig()
plt.close()
该错误被称为:ValueError:没有这样的数字:无
如何获得第二个“ Y”轴作为第二个值?
答案 0 :(得分:0)
通常,savefig
应先称为 show
。参见例如
第二,您想在创建的图形中生成图,而不是创建新图,因此使用
fig, ax = plt.subplots(figsize=...)
df.plot(..., ax=ax)
,然后调用轴的方法(面向对象的样式)。
总共
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
#######################
Val1 = [1,2,3,4,5,6,7,8,9,9,5,5] # in kWh
Val2 = [159,77,1.716246,2,4,73,128,289,372,347,354,302] #in m³
index = ['Apr', 'Mai', 'Jun', 'Jul','Aug','Sep','Okt','Nov','Dez','Jan', 'Feb', 'Mrz']
df = pd.DataFrame({'Val1': Val1,'Val2': Val2}, index=index)
with PdfPages('aas2s.pdf') as pdf:
plt.rc('text', usetex=True)
params = {'text.latex.preamble' : [r'\usepackage{siunitx}', r'\usepackage{amsmath}']}
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = 'Times New Roman'
plt.rcParams.update(params)
fig, ax = plt.subplots(figsize=(8, 6))
plt.rcParams.update({'font.size': 12})
df[['Val1','Val2']].plot.bar(color=['navy','maroon'], ax=ax)
ax.set_xlabel('X Achse m')
ax.set_ylabel('Y Achse Taxi quer ')
ax.legend(loc='upper left', frameon=False)
ax.set_title('Franz jagt im komplett verwahrlosten Taxi quer durch Bayern')
pdf.savefig()
plt.show()
plt.close()
现在,如果您仍然需要在显示该图形之后保存该图形,可以通过将其专门用作savefig
plt.show()
pdf.savefig(fig)