辅助y轴覆盖图例颜色并重置x-y刻度字体规范

时间:2014-12-15 16:24:22

标签: python-2.7 matplotlib plot axis-labels

我试图用Python 2.7在Matplotlib(散点图)中对一个x变量(轴)绘制2个y变量(主要和次要y轴)。

我首先创建2个x轴[twinx()]。然后我使用for循环绘制主y轴散点图 - 我必须使用循环来迭代Pandas数据帧的列,即x和y变量。然后我想使用第二个for循环来添加辅助y轴散点图。最后,我想添加一个由主要和辅助y轴变量名组成的图例。

但是,当我按照这些步骤操作时,我遇到了一些问题: 小号  1.图例符号的颜色不正确  2. 2个散点图中符号的颜色是相同的,所以看起来就像那里     没有次要的y轴  3. x和y-tick标签没有拾取正确的字体

以下是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
import matplotlib.cm as cm
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, FuncFormatter, AutoMinorLocator
from matplotlib import cm
import pandas as pd
from matplotlib.font_manager import FontProperties

# Loading data from *.csv file:
x_var = pd.DataFrame(np.random.rand(10,5),columns=['chan','top','lk_207','robt_sh','me_sh'])
y_var = pd.DataFrame(np.random.rand(10,5),columns=['values','count','chko','54_lib','941_dat'])
y_var_sec = pd.DataFrame(np.random.rand(10,5),columns=['header_max','two','bottom_7739','max_gain','low_ext'])

# List of primary and secondary x and y-variable names:
x_var_names = x_var.columns.tolist() #primary x variable list of names
y_var_names = y_var.columns.tolist() #primary y variable list of names
y_var_sec_names = y_var_sec.columns.tolist() #secondary y variable list of names

# Matplotlib plotting begins:
fig = plt.figure(1)
fig.set_facecolor('white')
ax = fig.add_subplot(111)
ax2=ax.twinx()

for j in range(0,len(x_var_names)): #Generate plot on primary y-axis
    ax.scatter(x_var[x_var_names[j]], y_var[y_var_names[j]], color=cm.jet(1.*j/len(x_var)), label=x_var_names[j])

ax.legend(y_var_names+y_var_sec_names, loc = 1, scatterpoints = 1)

# for label in ax2.get_xticklabels(): #NOT WOKRING
#   label.set_fontproperties(axis_tick_font)

title_font = {'fontname':'Times New Roman', 'size':'28', 'color':'black', 'weight':'bold','verticalalignment':'bottom'}
axis_font = {'fontname':'Constantia', 'size':'26'}
axis_tick_font = FontProperties(family='Times New Roman', style='normal', size=20, weight='normal', stretch='normal')
legend_fontsize = 20

ax.set_title(ax.get_title())
ax.grid(False)
ax.set_xlabel('Both X here_bottom',**axis_font)
ax.xaxis.set_label_position('bottom')
ax.set_ylabel('Primary Y here_left',**axis_font)
ax.xaxis.set_minor_locator(AutoMinorLocator(5))
ax.yaxis.set_minor_locator(AutoMinorLocator(5))
ax.tick_params(which='minor', length=5, width = 1)
ax.tick_params(direction='in')
ax.tick_params(which='major', width=1)
ax.tick_params(length=10)

ax2.set_ylabel('Secondary Y here_right',**axis_font)
ax2.yaxis.set_minor_locator(AutoMinorLocator(5))
ax2.tick_params(which='minor', length=5, width = 1)
ax2.tick_params(direction='in')
ax2.tick_params(which='major', width=1)
ax2.tick_params(length=10)

plt.show()

要得到辅助y轴图,我需要在scatter()代码中使用ax2,但我不知道如何让颜色从最后一个主轴颜色增加。我希望主要的y轴颜色与次要的y轴颜色不同。

  1. 如何在右侧(从循环内部)绘制x轴并从主y轴获得正确的不同颜色?
  2. 如何修复指定主要辅助轴'标记的字体属性?

0 个答案:

没有答案