python - 尽管在函数中生成,为什么我的绘图标签会发生变化?
问题描述
我有一些代码可以生成绘图并将绘图保存为.png
当前目录中的文件。出于某种原因,使用适合绘图面板的文本生成一个绘图,而第二个绘图(由相同的代码生成)实际上放大了轴文本标签。任何人都可以解释这种行为吗?
import pandas as pd
import matplotlib.pyplot as plt
import glob
import os
def get_basename(fp):
"Get the basename of filepath such that /PATH/TO/FILE.csv returns FILE"
return os.path.splitext(os.path.basename(fp))[0]
def get_model_type(fp, prefix):
"""All files represent models either 'linear' or 'quad'.
For instance all files are either linear_*_out.csv or quad_*_out.csv,
this function will filter a the list based on desired prefix"""
return filter(lambda x: get_basename(x).startswith(prefix), file_paths)
def read_assign(fp, col_name):
"""This function will read in the csv from input file path and assign
unique column identifier of the specific model. This will be important
when plotting the data"""
return pd.read_csv(fp).assign(model_id=col_name)
def produce_plot(df, plotname):
color_labels = df['model_id'].unique()
color_pal = ['black', 'red', 'cyan', 'brown', 'purple']
color_map = dict(zip(color_labels, color_pal))
grouped_sim = df.groupby('model_id')
for key, group in grouped_sim:
plt.plot(group['average_fuel_T'], group['avg_th_cond'],
label=key, color=color_map[key])
plt.ylabel('Thermal Conductivity', fontsize=20)
plt.xlabel('Temperature (K)', fontsize=20)
plt.legend(loc="upper left", prop=dict(weight='bold'))
plt.grid(b=True, which="major", axis="both", linestyle="-.")
plt.rc('xtick', labelsize=15)
plt.rc('ytick', labelsize=15)
plt.savefig(plotname)
plt.close()
working_dir = os.path.abspath('.')
file_paths = glob.glob(os.path.join(working_dir, '*_out.csv'))
linear_files = get_model_type(file_paths, 'linear')
linear_model_ids = [get_basename(file) for file in linear_files]
quad_files = get_model_type(file_paths, 'quad')
quad_model_ids = [get_basename(file) for file in quad_files]
raw_linear_dat = pd.concat(map(read_assign, linear_files, linear_model_ids))
raw_quad_dat = pd.concat(map(read_assign, quad_files, quad_model_ids))
produce_plot(raw_linear_dat, 'linear_temp_cond.png')
produce_plot(raw_quad_dat, 'quad_temp_cond.png')
解决方案
创建轴后设置 rc 参数。因此,它们将不适用于该轴,而仅适用于下一个轴。
确保在创建轴之前设置适用于轴的 rcParameters。
plt.rc('xtick', labelsize=15)
plt.rc('ytick', labelsize=15)
#only after that call...
plt.plot(...)
推荐阅读
- c++ - 我的程序不适用于 strcat - 我似乎不明白为什么?
- wordpress - wp_remote_request 不允许编辑帖子
- powershell - 使用 IFTTT 与 Google Assistance 和 Dropbox 一起使用 Powershell 打开 Spotify
- c# - C# Entity Framework - 如何在 Where 子句中动态传递值
- google-apps-script - 新的 Google 帐户无法访问 script.google.com
- gradle - 升级到 grails 3.1.13,现在无法解析类 org.grails.databinding.converters.web.LocaleAwareNumberConverter
- node.js - Strapi 中基于 Cookie 的身份验证
- sql - SQL/Postgres 加入 where 子句
- java - 转换 XML 时编译样式表错误
- visual-studio-code - 自最新更新以来,vscode 无法使用 javascript