对于大量绘图脚本,我使用 matplotlibs rcParams 为 pandas DataFrames 配置一些标准绘图设置。
这适用于颜色和字体大小,但不适用于描述的默认颜色图 here
这是我目前的做法:
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
# global plotting options
plt.rcParams.update(plt.rcParamsDefault)
matplotlib.style.use('ggplot')
plt.rcParams['lines.linewidth'] = 2.5
plt.rcParams['axes.facecolor'] = 'silver'
plt.rcParams['xtick.color'] = 'k'
plt.rcParams['ytick.color'] = 'k'
plt.rcParams['text.color'] = 'k'
plt.rcParams['axes.labelcolor'] = 'k'
plt.rcParams.update({'font.size': 10})
plt.rcParams['image.cmap'] = 'Blues' # this doesn't show any effect
# dataframe with random data
df = pd.DataFrame(np.random.rand(10, 3))
# this shows the standard colormap
df.plot(kind='bar')
plt.show()
# this shows the right colormap
df.plot(kind='bar', cmap=cm.get_cmap('Blues'))
plt.show()
只有当我像第二个情节一样将它作为参数传递时它才有效:
有什么方法可以永久定义 pandas DataFrame 图的标准颜色图吗?
提前致谢!
最佳答案
没有受支持的官方方法;你因为 pandas 的内部问题而卡住了 _get_standard_colors function对 matplotlib.rcParams['axes.color_cycle']
的使用进行硬编码并返回到 list('bgrcmyk')
:
colors = list(plt.rcParams.get('axes.color_cycle',
list('bgrcmyk')))
但是,您可以使用各种技巧;适用于所有 pandas.DataFrame.plot()
调用的最简单方法之一是包装 pandas.tools.plotting.plot_frame
:
import matplotlib
import pandas as pd
import pandas.tools.plotting as pdplot
def plot_with_matplotlib_cmap(*args, **kwargs):
kwargs.setdefault("colormap", matplotlib.rcParams.get("image.cmap", "Blues"))
return pdplot.plot_frame_orig(*args, **kwargs)
pdplot.plot_frame_orig = pdplot.plot_frame
pdplot.plot_frame = plot_with_matplotlib_cmap
pd.DataFrame.plot = pdplot.plot_frame
在笔记本中测试:
%matplotlib inline
import pandas as pd, numpy as np
df = pd.DataFrame(np.random.random((1000,10))).plot()
...产量:
关于python - Pandas DataFrame 图 : Permanently change default colormap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38761513/