PyPlot - 棘手的轴颜色和标签问题

时间:2017-03-30 20:52:25

标签: date pandas matplotlib plot yaxis

我对Matplotlib相当新。这个数字背后的想法是绘制温度高点和低点。我遇到了xaxis和yaxis的问题。

对于xaxis,即使我调用tick_params(labelcolor='#b6b6b6'),也不希望更改字体的颜色。此外,日期应仅跨越1月至12月。由于未知原因,Matplotlib正在增加额外的Dec并附加额外的Jan,导致文本流出图形的脊椎边界。我想删除这些额外的月份。

对于正确的yaxis,我不确定我是否理解正确使用子图。我想将左侧y轴中的˚C温度转换为˚F,并将转换后的温度用于次级y轴。

这里有一些代码可以重现类似于我所拥有的东西。

import numpy as np
import pandas as pd
import matplotlib as mpl 
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import matplotlib.ticker as ticker

# generate some data to plot
highs = np.linspace(0, 40, 365) # these numbers will escalate instead of fluctuate, but the problem with the axes will still be the same.
lows = np.linspace(-40, 0, 365)

date_rng = pd.date_range('1/1/2015', '12/31/2015', freq='D')

data = {'highs': highs, 'lows': lows}
to_plot = pd.DataFrame(data, index=date_rng)

fig, ax = plt.subplots()

# plot the basic data
lines = ax.plot(date_rng, to_plot['lows'], '-',
                date_rng, to_plot['highs'], '-')

# get the axes reference
ax1 = plt.gca()

# fill in between the lines
ax1.fill_between(date_rng,
                to_plot['lows'], to_plot['highs'],
                facecolor='#b6b6b6', # gradient fillbetween
                alpha=.2)

# set the xaxis to only 12 months and space the names.
ax1.xaxis.set_major_locator(dates.MonthLocator())
ax1.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15, interval=1))

ax1.xaxis.set_major_formatter(ticker.NullFormatter())
ax1.xaxis.set_minor_formatter(dates.DateFormatter('%b'))

for tick in ax1.xaxis.get_minor_ticks():
    tick.tick1line.set_markersize(0)
    tick.tick2line.set_markersize(0)
    tick.label1.set_horizontalalignment('center')

# add a right y axis and set all yaxis properties
ax1.set_ylim([-50, 50])

# change the color and sizes scheme 
info_colors = '#b6b6b6'
bold_colors = '#777777'

# graph lines
ax1.lines[0].set_color('#e93c00') # top redish orange
ax1.lines[1].set_color('#009ae9') # btm blue
plt.setp(lines, lw=.8, alpha=1)

# spines
ax.spines['top'].set_visible(False)
for pos in ['bottom', 'right', 'left']:
    ax.spines[pos].set_edgecolor(info_colors)

# set the title
plt.title('Record Temps, 2005-15: Ann Arbour, MI', fontsize=10, color=bold_colors)

# ticks
ax1.tick_params(axis='both', color=info_colors, labelcolor=info_colors, length=5, direction='out', pad=7, labelsize=8)

# add a legend and edit its properties
leg = plt.legend(['Highs','Lows'], frameon=False, loc=0, fontsize='small')
for text in leg.get_texts():
    text.set_color(info_colors)
    plt.ylabel('˚C', color=info_colors)

# set extra yaxis label
ax2 = ax.twinx()
ax2.set_ylabel('˚F', color=info_colors)
ax2.tick_params('y', colors=info_colors)

Plotted Temp Data

1 个答案:

答案 0 :(得分:0)

要更改次要标签的颜色,请在ax1.xaxis.set_minor_formatter(dates.DateFormatter('%b'))之后添加以下代码:

ax1.xaxis.set_tick_params(which='minor', colors=info_colors)

enter image description here