【问题标题】:Pandas DataFrame Plot: Permanently change default colormapPandas DataFrame Plot:永久更改默认颜色图
【发布时间】:2017-02-10 09:55:06
【问题描述】:

对于大量绘图脚本,我使用 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 绘图的标准颜色图吗?

提前致谢!

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    没有支持的官方方法;因为 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()
    

    ...产量:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      相关资源
      最近更新 更多