logo
down
shadow

Adding legend to a radarchart in Python


Adding legend to a radarchart in Python

By : Ari.Levy
Date : November 21 2020, 11:01 PM
it helps some times In case someone is interested, the code of the ComplexRadar comes from here.
The ComplexRadar class uses many axes and makes all of them invisible, so the best way to create a legend here, would be to create a new axes to put the legend in. For that we need the handles of the plotted lines, so we need to change the ComplexRadar.plot() method to return the line. We then need to collect those lines in a list (call it lax) and supply them to the new legend.
code :
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns 
import pandas as pd

def _scale_data(data, ranges):
    """scales data[1:] to ranges[0],
    """
    for d, (y1, y2) in zip(data[1:], ranges[1:]):
        assert (y1 <= d <= y2) or (y2 <= d <= y1)
    x1, x2 = ranges[0]
    d = data[0]
    sdata = [d]
    for d, (y1, y2) in zip(data[1:], ranges[1:]):
        sdata.append((d-y1) / (y2-y1) 
                     * (x2 - x1) + x1)
    return sdata

class ComplexRadar():
    def __init__(self, fig, variables, ranges,
                 n_ordinate_levels=6):
        angles = np.arange(0, 360, 360./len(variables))

        axes = [fig.add_axes([0.1,0.1,0.9,0.9],polar=True,
                label = "axes{}".format(i)) 
                for i in range(len(variables))]
        l, text = axes[0].set_thetagrids(angles, 
                                         labels=variables)
        [txt.set_rotation(angle-90) for txt, angle 
             in zip(text, angles)]
        for ax in axes[1:]:
            ax.patch.set_visible(False)
            ax.grid("off")
            ax.xaxis.set_visible(False)
        for i, ax in enumerate(axes):
            grid = np.linspace(*ranges[i], 
                               num=n_ordinate_levels)
            gridlabel = ["{}".format(round(x,2)) 
                         for x in grid]
            if ranges[i][0] > ranges[i][1]:
                grid = grid[::-1] # hack to invert grid
                          # gridlabels aren't reversed
            gridlabel[0] = "" # clean up origin
            ax.set_rgrids(grid, labels=gridlabel,
                         angle=angles[i])
            #ax.spines["polar"].set_visible(False)
            ax.set_ylim(*ranges[i])
        # variables for plotting
        self.angle = np.deg2rad(np.r_[angles, angles[0]])
        self.ranges = ranges
        self.ax = axes[0]

    def plot(self, data, *args, **kw):
        sdata = _scale_data(data, self.ranges)
        l = self.ax.plot(self.angle, np.r_[sdata, sdata[0]], *args, **kw)
        return l

    def fill(self, data, *args, **kw):
        sdata = _scale_data(data, self.ranges)
        self.ax.fill(self.angle, np.r_[sdata, sdata[0]], *args, **kw)



index = ["Carl","Michael","Peter","Louis","Sarah", "Laura","Nicholas"]      
df = pd.DataFrame({
    "Spe": pd.Series([89, 83, 70, 60, 30, 49, 28]),
    "Str": pd.Series([69, 53, 30, 20, 10, 29, 48]),
    "Det": pd.Series([82, 44, 79, 39, 20, 10, 85]),
    "Extr": pd.Series([59, 74, 29, 36, 18, 29, 18]),
    "Int": pd.Series([63, 11, 20, 36, 97, 58, 91]),
    "Est": pd.Series([12, 69, 89, 59, 19, 58, 98]),
    "Ape": pd.Series([29, 13, 94, 30, 20, 10, 67]),
})

variables = [k[0] for k in df.iteritems()]

ranges = [(1.,100.),(1.,100.),(1.,100.),(1.,100.),(1.,100.),(1.,100.),(1.,100.)] 
fig1 = plt.figure(figsize=(8, 8))
radar = ComplexRadar(fig1, variables, ranges)
lax = []
for i, name  in enumerate(index):
    data=df.iloc[i].values
    l, = radar.plot(data, label=name)
    lax.append(l)
    radar.fill(data,alpha=0.2)

legendax = fig1.add_axes([0.8,0.8,0.1,.1])
legendax.legend(handles = lax, labels=index, loc=3, bbox_to_anchor=(0,0,1,1), bbox_transform=fig1.transFigure )

legendax.axis('off')
sns.plt.show()


Share : facebook icon twitter icon
Adding Legends to a radarchart

Adding Legends to a radarchart


By : Chasing Rainbows inc
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Here's a generic legend to get you started. You can alter it to suit your particular needs:
code :
legend(-2,0,
       legend=c("V1","V2"),
       pch=c(15,16),
       col=c("blue","red"),
       lty=c(1,2))
Adding legend entry makes all other legend entries diagonal and rectangles

Adding legend entry makes all other legend entries diagonal and rectangles


By : nurisa unindra
Date : March 29 2020, 07:55 AM
it helps some times One way to remove lines from the colour and size legends is to set linetype=0 inside override.aes= for colour= and size=
code :
 + guides(colour = guide_legend(override.aes = list(size=6,linetype=0)),
        size = guide_legend(override.aes=list(linetype=0)))
Adding legend to scatter plot in Python

Adding legend to scatter plot in Python


By : Michael AMA
Date : March 29 2020, 07:55 AM
seems to work fine The idea is to divide data set on separate data sets which are represented by the same color. After that the legend displayed properly.
code :
import matplotlib.pyplot as plt
import matplotlib
import numpy as np

data = np.zeros(shape=(10,2))
data[:,0] = np.linspace(0,1,10)
data[:,1] = np.linspace(0,1,10)

y = ['red', 'green', 'blue']
f, ax1 = plt.subplots(3,2)
cmap = matplotlib.cm.get_cmap('coolwarm')
ny = len(y)
for i, itm in enumerate(y):
    datac = data[i::ny,:]
    ax1[0,1].scatter(datac[:,0], datac[:,1], c=itm, 
                     s=20, marker='o', alpha=.5, cmap=cmap)

ax1[0,1].legend(['label1', 'label2', 'label3'],
           scatterpoints=1,
           loc='lower left',
           fontsize=10)
plt.show()
Legend label is not adding for multiple plots in python

Legend label is not adding for multiple plots in python


By : Deathstreams
Date : March 29 2020, 07:55 AM
wish of those help Set lebel argument when plot and use handle to make a legend. Try to write like this:
code :
def runplot(df, title, label):   
    rows, cols = df.shape

    fig, ax = plt.subplots()
    line1, = ax.plot(df['price'].values, df['cost'].values, label=label)
    ax.legend(handles=[line1])

    plt.title(title)
    plt.annotate('test!', 
                 xy=(rows, df.ix[rows-1,'cost']),  
                 xycoords='data',
                 xytext=(-30,30),
                 textcoords='offset points',
                 arrowprops=dict(arrowstyle="->"))
error of adding a legend for a plot in Python 3.2 Matplotlib

error of adding a legend for a plot in Python 3.2 Matplotlib


By : ron gerard valero
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I need to add a legend for a plot in Python 3.2 Matplotlib. , Here's what should work
Related Posts Related Posts :
  • Django Form Based on Variable Attributes
  • Relocate all the evens
  • How to scrap span ids' texts in beautifulsoup in the following html?
  • How to generate random number in a given range as a Tensorflow variable
  • Gradient Descent Variation doesn't work
  • Python 2.7 - search for a particular URL on a webpage with ajax
  • How to configure Luigi task retry correctly?
  • web.py : an urlencoded slash into args
  • Use of pyzmq's logging handler in python
  • How to count the number of a particular entry. python
  • devide int into lower whole ints
  • Access atribute of every object in pandas dataframe column
  • Combine Dataframe rows on conditions
  • Select closest date (or value) in pandas / python
  • Pycharm and remote interpreter (Docker) shows errors but runs fine
  • Get started to launch google-cloud-ml with my own dataset
  • Multiprocessing: use only the physical cores?
  • Django Login Custom Auth works locally but not on production server
  • Python: Invalid HTTP basic authentication header with long base64 string
  • How can I request several pages without wating for the output?
  • Flask Response vs Flask make_response
  • python linear regression predict by date
  • How to get pandas dataframe where columns are the subsequent n-elements from another column dataframe?
  • MYSQL: "Access denied for user 'X'@'localhost' (using password: YES)" PYTHON
  • install scipy package via pycharm in windows 10 64 bit - python 3.5
  • Update time in linux and solaris machines from robot framework
  • Complex pandas isin function
  • Averaging over every n elements of an array without numpy
  • An elegant way of inserting multiple arguments
  • IntegrityError:NOT NULL constraint failed: chatapp_chat.message
  • Indexing of 3d numpy arrays with 2d arrays
  • Creating a mean of columns with csv writer
  • Reading in environment variables from an environment file
  • Collapse duplicate rows with pandas
  • How can I use skyfied to convert SGP4 TEME coordinate to ECEF?
  • How to modify object in Python's Rtree index
  • Create Hexbin plot with pandas dataframe using index and columns names as x and y
  • SQLAlchemy query returns no data if a database field is empty
  • Python pandas column asignment between dataframe and series does not work
  • ValueError: Unknown label type: array while using Decision Tree Classifier and using a custom dataset
  • Trouble accessing exif information with PIL.Image._getexif()
  • Use all coordinates in a grid except with certain value
  • Why for loop is splitting strings of user input?
  • How can I add two variable and assign to result variable in Python?
  • Error when parsing timestamp with pandas read_csv
  • Slicing arrays based on boolean array in python
  • Feeding scipy.sparse() sparse matrices into CVXOPT
  • How to separate a irregularly cased string to get the words? - Python
  • Pandas: replace some values in column if that contain a substring
  • Fabric does not close the ssh connection
  • Python Creating Classes Code
  • When will train() method in easy_seq2seq stop?
  • How to split each element of the RDD in spark with python?
  • Read in csv file in python, round the values and write back to file
  • How to properly close a QWidget-window in an API with PythonQt
  • How to know which segment a value reside in
  • pandas: convert multiple categories to dummies
  • 'Options' object has no attribute 'get_all_field_names'
  • Customize django filter model field
  • NLTK tag Dutch sentence
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com