Adding color to radar chart in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • swisha
    New Member
    • Mar 2020
    • 5

    Adding color to radar chart in python

    Hello,

    What code do I use to change the color background of a radar chart using python.
    I want to use a sequential color scheme from light blue to dark blue.
    I assume that the starting point would be from matplotlib.pypl ot using the cmaps.

    Any help is appreciated.
  • SioSio
    Contributor
    • Dec 2019
    • 272

    #2
    col indicates an RGB color between 0.0 and 1.0.
    It can change the background color by adjusting RGB.
    Code:
        fig = plt.figure()
    :
    :
    :
        col = [0.0, 0.0, 1.0]
        fig.savefig(imgname, facecolor=col)

    Comment

    • swisha
      New Member
      • Mar 2020
      • 5

      #3
      Thanks for the help.

      How do I code the 'Blues' from the sequential colormap as found on this page: https://matplotlib.org/tutorials/colors/colormaps.html

      Comment

      • SioSio
        Contributor
        • Dec 2019
        • 272

        #4
        Hexadecimal or RGB specified, change the blue color as shown below.
        '#0000ff' is the same as [0.0, 0.0, 1.0].
        Code:
        fig = plt.figure()
        col1 = [0.3, 0.2, 0.5]
        col2 = [0.2, 0.3, 0.5]
        col3 = [0.1, 0.3, 0.5]
        col4 = [0.0, 0.3, 0.6]
        col5 = [0.0, 0.3, 0.7]
        col6 = [0.0, 0.2, 0.8]
        col7 = [0.0, 0.1, 0.9]
        colorlist = [col1, col2, col3, col4, col5, col6, col7, '#0000ff']
        x = np.arange(1, 9)
        height = np.arange(1, 9)
        plt.barh(x, height, color=colorlist, tick_label=colorlist, align="center")
        fig.savefig("test1.png")

        Comment

        • swisha
          New Member
          • Mar 2020
          • 5

          #5
          Where would I code that into this example. I want to change the background of the radar chart with the "Blues' Sequential colormap.
          Code:
          # Plots a radar chart.
           
          from math import pi
          import matplotlib.pyplot as plt
           
           
          # Set data
          cat = ['Speed', 'Reliability', 'Comfort', 'Safety', 'Effieciency']
          values = [90, 60, 65, 70, 40]
           
          N = len(cat)
           
          x_as = [n / float(N) * 2 * pi for n in range(N)]
           
          # Because our chart will be circular we need to append a copy of the first 
          # value of each list at the end of each list with data
          values += values[:1]
          x_as += x_as[:1]
           
           
          # Set color of axes
          plt.rc('axes', linewidth=0.5, edgecolor="#888888")
           
           
          # Create polar plot
          ax = plt.subplot(111, polar=True)
           
           
          # Set clockwise rotation. That is:
          ax.set_theta_offset(pi / 2)
          ax.set_theta_direction(-1)
           
           
          # Set position of y-labels
          ax.set_rlabel_position(0)
           
           
          # Set color and linestyle of grid
          ax.xaxis.grid(True, color="#888888", linestyle='solid', linewidth=0.5)
          ax.yaxis.grid(True, color="#888888", linestyle='solid', linewidth=0.5)
           
           
          # Set number of radial axes and remove labels
          plt.xticks(x_as[:-1], [])
           
          # Set yticks
          plt.yticks([20, 40, 60, 80, 100], ["20", "40", "60", "80", "100"])
           
           
          # Plot data
          ax.plot(x_as, values, linewidth=2, linestyle='solid', zorder=3)
           
          # Fill area
          ax.fill(x_as, values, 'b', alpha=0.0)
           
           
          # Set axes limits
          plt.ylim(0, 100)
           
           
          # Draw ytick labels to make sure they fit properly
          for i in range(N):
              angle_rad = i / float(N) * 2 * pi
           
              if angle_rad == 0:
                  ha, distance_ax = "center", 10
              elif 0 < angle_rad < pi:
                  ha, distance_ax = "left", 1
              elif angle_rad == pi:
                  ha, distance_ax = "center", 1
              else:
                  ha, distance_ax = "right", 1
           
              ax.text(angle_rad, 100 + distance_ax, cat[i], size=10, horizontalalignment=ha, verticalalignment="center")
           
           
          # Show polar plot
          plt.show()
          Thanks for the help. I am a total beginner with python.

          Comment

          • SioSio
            Contributor
            • Dec 2019
            • 272

            #6
            Ex.
            Write at the beginning of the code.
            Code:
            import matplotlib.pyplot as plt
            import numpy as np
            from math import pi
            
            col1 = [0.0,0.0,1.0]
            fig = plt.figure()
            fig.patch.set_facecolor(col1)

            Comment

            • swisha
              New Member
              • Mar 2020
              • 5

              #7
              Thanks for the reply but not quite what I was after but helpful.

              How do I change color of the actual chart with a sequential background, starting from blue in the middle of the circle to light blue on the outer edges?

              Comment

              • SioSio
                Contributor
                • Dec 2019
                • 272

                #8
                Use matplotlib.pypl ot.fill_between .
                However, I do not know how to fill in a circle.
                Code:
                ax.fill_between(x_as, 0, 20, color=col1)
                ax.fill_between(x_as, 20, 40, color=col2)
                ax.fill_between(x_as, 40, 60, color=col3)
                ax.fill_between(x_as, 60, 80, color=col4)
                ax.fill_between(x_as, 80, 100, color=col5)

                Comment

                • lewish95
                  New Member
                  • Mar 2020
                  • 33

                  #9
                  Code:
                  # Libraries
                  import matplotlib.pyplot as plt
                  import pandas as pd
                  from math import pi
                   
                  # Set data
                  df = pd.DataFrame({
                  'group': ['A','B','C','D'],
                  'var1': [38, 1.5, 30, 4],
                  'var2': [29, 10, 9, 34],
                  'var3': [8, 39, 23, 24],
                  'var4': [7, 31, 33, 14],
                  'var5': [28, 15, 32, 14]
                  })
                   
                  # ------- PART 1: Define a function that do a plot for one line of the dataset!
                   
                  def make_spider( row, title, color):
                   
                  # number of variable
                  categories=list(df)[1:]
                  N = len(categories)
                   
                  # What will be the angle of each axis in the plot? (we divide the plot / number of variable)
                  angles = [n / float(N) * 2 * pi for n in range(N)]
                  angles += angles[:1]
                   
                  # Initialise the spider plot
                  ax = plt.subplot(2,2,row+1, polar=True, )
                   
                  # If you want the first axis to be on top:
                  ax.set_theta_offset(pi / 2)
                  ax.set_theta_direction(-1)
                   
                  # Draw one axe per variable + add labels labels yet
                  plt.xticks(angles[:-1], categories, color='grey', size=8)
                   
                  # Draw ylabels
                  ax.set_rlabel_position(0)
                  plt.yticks([10,20,30], ["10","20","30"], color="grey", size=7)
                  plt.ylim(0,40)
                   
                  # Ind1
                  values=df.loc[row].drop('group').values.flatten().tolist()
                  values += values[:1]
                  ax.plot(angles, values, color=color, linewidth=2, linestyle='solid')
                  ax.fill(angles, values, color=color, alpha=0.4)
                   
                  # Add a title
                  plt.title(title, size=11, color=color, y=1.1)
                   
                  # ------- PART 2: Apply to all individuals
                  # initialize the figure
                  my_dpi=96
                  plt.figure(figsize=(1000/my_dpi, 1000/my_dpi), dpi=my_dpi)
                   
                  # Create a color palette:
                  my_palette = plt.cm.get_cmap("Set2", len(df.index))
                   
                  # Loop to plot
                  for row in range(0, len(df.index)):
                  make_spider( row=row, title='group '+df['group'][row], color=my_palette(row))
                  I hope this code helps!
                  Last edited by gits; Mar 10 '20, 02:08 PM. Reason: added code tags

                  Comment

                  Working...