matplotlib 2种不同PC中的不同颜色

时间:2018-07-03 22:19:52

标签: python matplotlib colors color-scheme

今天,我在python中开发了一个简单的类,以便获得适合自己目的的绘图样式... 这里是班级: 这是我在其中定义颜色的基类...在函数colors中,我特别感兴趣的是名为“ soft”的颜色循环

from abc import ABCMeta, abstractmethod
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter 
from matplotlib.axes import Axes
import matplotlib.pylab as pylab
import matplotlib
from cycler import cycler


class PlotBase(metaclass=ABCMeta):

   def __init__(self, title , filename : str = ' '):
      self.title = title
      self.filename = filename   

#----------------------------------------------------------------------------------------------
   def findLimits(self):
         '''
             found the vectors limits in order to set the figure limits x,y
         '''
         _minX = 10E20
         _minY = 10E20
         _maxX = 0.000
         _maxY = 0.000
         for i in range(0,len(self.variable)-1,3):
            if _minX >= min(self.variable[i]):  
               _minX = min(self.variable[i])
            if _maxX <= max(self.variable[i]):
               _maxX = max(self.variable[i])
            if _minY >= min(self.variable[i+1]):  
               _minY = min(self.variable[i+1])
            if _maxY <= max(self.variable[i+1]):
               _maxY = max(self.variable[i+1])
         return [round(_minX,2), round(_maxX,2) , round(_minY,2) , round(_maxY,2)]

#------------------------------------------------------------------------------------------------
   def save(self, filename : 'str -> name of the file with extension'):
       plt.savefig(filename)
#------------------------------------------------------------------------------------------------

   def colors(self, style : 'str (name of the pallette of line colors)'):
      if style == 'vega':
         style = "cycler('color', ['1F77B4', 'FF7F0E', '2CA02C', 'D62728', '9467BD', '8C564B', 'E377C2', '7F7F7F', 'BCBD22', '17BECF'] )" 
      elif style == 'gg': 
         style = "cycler('color', ['E24A33', '348ABD', '988ED5', '777777', 'FBC15E', '8EBA42', 'FFB5B8'])"
      elif style == 'brewer':           
         style = "cycler('color', ['66C2A5', 'FC8D62', '8DA0CB', 'E78AC3', 'A6D854', 'FFD92F', 'E5C494', 'B3B3B3'] )"
      elif style == 'soft1':   
         style = "cycler('color', ['8DA0CB', 'E78AC3', 'A6D854', 'FFD92F', 'E5C494', 'B3B3B3', '66C2A5', 'FC8D62'] )"
      elif style == 'tthmod':      
         style = "cycler('color', ['30a2da', 'fc4f30', 'e5ae38', '6d904f', '8b8b8b'])"
      elif style == 'grayscale':
         style = "cycler('color', ['252525', '525252', '737373', '969696', 'BDBDBD', 'D9D9D9', 'F0F0F0', 'F0F0FF' ])"
      elif style == 'grayscale2':
         style = "cycler('color', ['525252', '969696', 'BDBDBD' ,'D9D9D9', 'F0F0F0', 'F0F0FF' ])"
      return style  

#------------------------------------------------------------------------------------------------

   def linestyle(self , linestyle : str):
      if linestyle == 'linetype1':
         linestyle = "cycler('linestyle', ['-', '--', ':', '-.'])"
      if linestyle == 'linetype2':
         linestyle = "cycler('linestyle', ['-', ':', '-.', '--'])"
      return linestyle
#------------------------------------------------------------------------------------------------
   @abstractmethod
   def plot(self,*args,**kwargs):
      """
         Abstract method!
         the derived class must implement its self method 
      """
      pass

然后定义可用的可调用类:

class TimesPlot(PlotBase):
   '''   
         mathpazo style (LaTeX-class) plot suitable for:
           - palatino fonts template / beamer 
           - classic thesis style 
           - mathpazo package 
   '''
   def __init__(self,title,filename: str= ' '):
         super().__init__(title,filename)


#------------------------------------------------------------------------------------------------------------

   def plot(self, *args,**kwargs):   #   

         self.variable = [*args]
         if len(self.variable) % 3 != 0:
            print('Error variable must be coupled (even number)')
            raise AttributeError('you must give 2 array x,y followed by string label for each plot')
         '''  
               plot method, define all the parameter for the plot
               the rendering of the figure is setting to beh "light" 

               -->   TODO : define parameter in order to set the size of figure/font/linewidth
         '''

         #plt.rc('text', usetex=True )
         #plt.rcParams['text.latex.preamble']=[r"\usepackage{times}"]
         #plt.rcParams['text.latex.preamble']=[r"\usepackage{mathpazo}"]

         plt.rcParams['font.family'] = 'serif'   #'serif'
         #plt.rcParams['font.sans-serif'] = ''#'DejaVu Sans' #'Tahoma' #, , 'Lucida Grande', 'Verdana']
         plt.rcParams['font.size'] = 14
         #plt.rcParams['font.name'] = 'Helvetica'
         plt.rcParams['font.style'] = 'italic'
         #plt.rc('font',family='' ,size=16, weight='normal')



         plt.rc_context({'axes.edgecolor':'#999999' })   # BOX colors
         plt.rc_context({'axes.linewidth':'1' })   # BOX width
         plt.rc_context({'axes.xmargin':'0' })     
         plt.rc_context({'axes.ymargin':'0' })     
         plt.rc_context({'axes.labelcolor':'#555555' })     
         plt.rc_context({'axes.edgecolor':'999999' })     
         plt.rc_context({'axes.axisbelow':'True' })     
         plt.rc_context({'xtick.color':'#555555' })   # doesn't affect the text
         plt.rc_context({'ytick.color':'#555555' })   # doesn't affect the text
         plt.rc_context({ 'axes.prop_cycle': self.colors('soft1')}) 

         #plt.rc('lines', linewidth=3)

         fig,ax = plt.subplots(1,figsize=(10,6))



         plt.title(self.title,color='#555555',fontsize=18)
         plt.xlabel('time [s]',fontsize=16)
         plt.ylabel('y(t)',fontsize=16)
         #plt.grid(linestyle='dotted')
         plt.grid(linestyle='--')
         #plt.figure(1)
                  #ax.edgecolor('gray')
         for i in range(0,len(self.variable)-1,3):
            plt.plot(self.variable[i],self.variable[i+1], linewidth=3, label= self.variable[i+2])   

         ax.set_xlim( self.findLimits()[0] , self.findLimits()[1] )
         ax.set_ylim( self.findLimits()[2] , self.findLimits()[3] + 0.02 )

         majorLocator    = MultipleLocator(20)
         majorFormatter  = FormatStrFormatter('%f')
         minorXLocator   = MultipleLocator(0.05)
         minorYLocator   = MultipleLocator(0.05)

         ax.xaxis.set_minor_locator(minorXLocator)
         ax.yaxis.set_minor_locator(minorYLocator)
         ax.yaxis.set_ticks_position('both')
         ax.xaxis.set_ticks_position('both')

         #axes.xmargin: 0
         #axes.ymargin: 0

         #plt.legend(fontsize=10)
         #handles, labels = ax.get_legend_handles_labels()
         #ax.legend(handles, labels)
         #ax.legend(frameon=True, fontsize=12)

         #text.set_color('gray')
         #leg = plt.legend(framealpha = 0, loc = 'best')
         #ax.legend(borderpad=1)
         legend = leg = plt.legend(framealpha = 1, loc = 'best', fontsize=14,fancybox=False, borderpad =0.4)
         leg.get_frame().set_edgecolor('#dddddd')
         leg.get_frame().set_linewidth(1.2)
         plt.setp(legend.get_texts(), color='#555555')

         plt.tight_layout(0.5)
         if self.filename != ' ': 
            super().save(self.filename)
         plt.show()

之所以会发生这种情况,是因为在我的大学PC上,该课程给我一个使用soft1配色方案的情节...在家里使用相同版本的python。它使用默认的一组颜色(对应于我定义的名为' vega')...不仅线条颜色发生变化...情节的方框中的颜色对比度也不同...有人可以帮助我吗?

我称这个类为它们简单地传递6个矢量(以获得3条曲线),如下所示:

  fig1 = makeplot.TimesPlot('Solution of Differential Equations','p1.pdf')
   fig1.plot(fet,feu,'Explicit Euler',bet,beu,'Implicit Euler',x,y,'Analytical')

能否请您帮助我了解发生这种情况的原因?我在家里用archlinux和gentoo ....尝试过,而在可以正常使用该类的台式机上,我使用了最后一个debian

0 个答案:

没有答案
相关问题