python matplotlib图例重复

2024-06-17 10:00:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

“唤醒”与“睡眠-快速眼动”是同一颜色

{1美元^

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

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()

Tags: alphadfsizebin颜色createpltseries
2条回答

plot有一个color参数。您可以为每列使用不同的颜色。例如

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()

@Evert的评论起到了帮助作用

You define your own set of (cyclic) colours. Simple example at matplotlib.org/examples/color/color_cycle_demo.html , and available colours at matplotlib.org/gallery.html#color . – Evert

修改了上面的pydef函数:

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 ) ) )

相关问题 更多 >