python matplotlib传奇重复

时间:2017-09-19 22:08:02

标签: python matplotlib

我有一个带有直方图的子图。朝向底部的plt.legend创建了一个颜色重复的图例。在子图的部分截图中,

"激醒"与" SLEEP-REM"

的颜色相同

如何更改图表和图例的颜色以使它们都是唯一的?

def create_histogram( grouped, axs, df ):
    bin_size = 100
    alpha = 0.5
    grouped = df.groupby( 'Label' )

    bins = np.linspace( df.Capacitor_1.min(), df.Capacitor_1.max(), bin_size )
    series = grouped.Capacitor_1
    series.plot( kind = 'hist', title = "Capacitor 1", ax = axs[0][0] , bins = bins, alpha = alpha )

    ...

    bins = np.linspace( df.Mag_Z.min(), df.Mag_Z.max(), bin_size )
    series = grouped.Mag_Z
    series.plot( kind = 'hist', title = "Mag Z", ax = axs[3][2], bins = bins, alpha = alpha )

fig, axs = plt.subplots( nrows = 4, ncols = 3, figsize = ( 20, 40 ) )
fig.subplots_adjust( hspace = .5 )
grouped = df_left.groupby( 'Label' )
create_histogram( grouped, axs, df_left )
plt.legend( bbox_to_anchor = ( 0.98, 0.8 ) )
plt.show()

2 个答案:

答案 0 :(得分:0)

plotcolor个参数。您可以为每列使用不同的颜色。例如

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

n_columns = 4
df = pd.DataFrame(
    np.random.randn(1000, n_columns), 
    columns=['col{}'.format(i) for i in range(n_columns)]
)

df.col0.plot(kind='hist', color='b')
df.col1.plot(kind='hist', color='c')
df.col2.plot(kind='hist', color='g')
df.col3.plot(kind='hist', color='k')

plt.legend()

答案 1 :(得分:0)

来自@Evert的评论帮助

  

您可以定义自己的一组(循环)颜色。       matplotlib.org/examples/color/color_cycle_demo.html处的简单示例以及matplotlib.org/gallery.html#color处的可用颜色。 - 外翻

我在上面修改了pyplot函数def:

import matplotlib.pyplot as plt
from cycler import cycler

palette = ['#ff0000', '#663600', '#a3cc00', '#80ffc3', '#0088ff', '#d9bfff', '#a6296c', '#8c4646', '#ff8800', '#5e664d', '#269991', '#1d3f73', '#7e468c', '#d96236', '#7f2200']

# 1. Setting prop cycle on default rc parameter
plt.rc( 'lines', linewidth = 4 )
plt.rc( 'axes', prop_cycle = ( cycler( 'color', palette ) ) )