首页 > 解决方案 > matplotlib 在 2 台不同的电脑上使用不同的颜色

问题描述

今天我在python中开发了一个简单的类,以获得适合我的目的的绘图风格......这里的类:这是我定义颜色的基类......在函数颜色中,我特别感兴趣的是名为“软”的颜色循环

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

之所以会跌倒是因为在我的大学电脑中,这门课给了我一个使用 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

标签: pythonmatplotlibcolorscolor-scheme

解决方案


推荐阅读