在matplotlib中更改绘图的轴,刻度和标签的颜色

Ric*_*urr 76 python pyqt colors matplotlib

我想更改轴的颜色,以及使用matplotlib和PyQt绘制的绘图的刻度和值标签.

有任何想法吗?

Joe*_*ton 129

作为一个简单的例子(使用比可能重复的问题稍微清晰的方法):

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')

plt.show()
Run Code Online (Sandbox Code Playgroud)

替代文字

  • 嗯......那很奇怪......你用的是什么版本的matplotlib?一个解决方法是对ax.xaxis.get_ticklines()中的t执行`[t.set_color('red')for ax.xaxis.get_ticklines()]和`[t.set_color('red')for t. . (13认同)

joe*_*lom 28

如果您要修改多个图形或子图,使用matplotlib上下文管理器更改颜色可能会有所帮助,而不是单独更改每个颜色.上下文管理器允许您仅为紧随其后的缩进代码临时更改rc参数,但不会影响全局rc参数.

这个片段产生两个数字,第一个是轴,刻度和刻度标签的修改颜色,第二个是默认的rc参数.

import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
    # Temporary rc parameters in effect
    fig, (ax1, ax2) = plt.subplots(1,2)
    ax1.plot(range(10))
    ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在此输入图像描述

您可以键入plt.rcParams以查看所有可用的rc参数,并使用列表推导来搜索关键字:

# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]
Run Code Online (Sandbox Code Playgroud)


Tre*_*ney 6

  • 对于那些使用pandas.DataFrame.plot(),matplotlib.axes.Axes在从数据框创建绘图时返回的人。因此,可以将数据框图分配给变量ax,从而可以使用相关的格式化方法。
  • , 的默认绘图后端pandasmatplotlib
import pandas as pd

# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)

# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))

# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red') 
ax.spines['right'].set_color('magenta')
ax.spines['left'].set_color('orange')
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both')  # 'both' refers to minor and major axes
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明