How do you just show the text label in plot legend? (e.g. remove a label's line in the legend)
matplotlib legend two columns
matplotlib custom legend
no handles with labels found to put in legend. matplotlib
matplotlib legend only shows first letter
matplotlib colormap legend
matplotlib legend based on color
matplotlib legend opaque
I want to show the text for a line's label in the legend, but not a line too (As shown in the figure below):
I have tried to minimise the legend's line and label, and overwrite only the new-label too (as in the code below). However, the legend brings both back.
legend = ax.legend(loc=0, shadow=False) for label in legend.get_lines(): label.set_linewidth(0.0) for label in legend.get_texts(): label.set_fontsize(0) ax.legend(loc=0, title='New Title')
At that point, it's arguably easier to just use
import numpy as np import matplotlib.pyplot as plt data = np.random.normal(0, 1, 1000).cumsum() fig, ax = plt.subplots() ax.plot(data) ax.annotate('Label', xy=(-12, -12), xycoords='axes points', size=14, ha='right', va='top', bbox=dict(boxstyle='round', fc='w')) plt.show()
However, if you did want to use
legend, here's how you'd do it. You'll need to explicitly hide the legend handles in addition to setting their size to 0 and removing their padding.
import numpy as np import matplotlib.pyplot as plt data = np.random.normal(0, 1, 1000).cumsum() fig, ax = plt.subplots() ax.plot(data, label='Label') leg = ax.legend(handlelength=0, handletextpad=0, fancybox=True) for item in leg.legendHandles: item.set_visible(False) plt.show()
How do you just show the text label in plot legend? (eg remove a , At that point, it's arguably easier to just use annotate . For example: import numpy as np import matplotlib.pyplot as plt data I'm using legend and I want to remove the colored labels and keep only the text in the legend (Matlab 2018b). Is there any way to do that? (I tried using annotation, I don't want the box to be there - just text)
I found another much simpler solution - simply set the scale of the marker to zero in the legend properties:
This is particularly useful in scatter plots, when you don't want the marker to be visually mistaken for a true data point (or even outlier!).
Matplotlib Examples: Displaying and Configuring Legends, Add legend to plot; Add legend to multiple plots in the same axis; Add legend plt.plot(x,y) # call method plt.legend plt.legend(['line plot 1']) plt.show() While you can just pass a list with multiple texts to plt.legend(), it's better to label each reason and you want to get rid of them, call ax.legend_.remove(). To make a legend for lines which already exist on the axes (via plot for instance), simply call this function with an iterable of strings, one for each legend item. For example:: ax.plot([1, 2, 3]) ax.legend(['A simple line'])
You can just set the
handlelength in the legend via the
legend_handler as shown below:
import matplotlib.pyplot as plt import numpy as np # Plot up a generic set of lines x = np.arange( 3 ) for i in x: plt.plot( i*x, x, label='label'+str(i), lw=5 ) # Add a legend # (with a negative gap between line and text, and set "handle" (line) length to 0) legend = plt.legend(handletextpad=-2.0, handlelength=0)
handlelength is in documentation (linked here, & copied below):
handletextpad : float or None
The pad between the legend handle and text. Measured in font-size units. Default is None, which will take the value from rcParams["legend.handletextpad"].
handlelength : float or None
The length of the legend handles. Measured in font-size units. Default is None, which will take the value from rcParams["legend.handlelength"].
With the above code:
With a few extra lines the labels can have the same color as their line. just use
# Now color the legend labels the same as the lines color_l = ['blue', 'orange', 'green'] for n, text in enumerate( legend.texts ): print( n, text) text.set_color( color_l[n] )
Legend guide, If len(args) is 0, it automatically generate the legend from label properties of the child The label attributes (returned by get_label() method) of collected artists are used as text labels. complex plots that creates multiple artists (e.g., bar, errorbar, etc); custom However, the above code only shows the second legend. 85. If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command. import pandas as pd import numpy as np import matplotlib.pyplot as plt df2 = pd.DataFrame(np.random.randn(10, 5)) df2.plot(legend=None) plt.show() share. Share a link to this answer.
Suggesting the best answer:
handlelength=0, for example:
matplotlib.pyplot.legend, line.set_label('Label via method') line, = ax.plot([1, 2, 3]) ax.legend() Note: This way of using is discouraged, because the relation between plot elements and labels is only implicit by their order and can easily be mixed up. A list of labels to show next to the artists. 0.0 is at the base the legend text, and 1.0 is at the top. If a plot already has a title, subtitle, caption, etc., and you want to remove it, you can do so by setting the respective argument to NULL. For example, if plot p has a subtitle, then p + labs(subtitle = NULL) will remove the subtitle from the plot.
GGPlot Legend Title, Position and Labels, Change the legend title and text labels; Modify the legend position. Example of R code: p + guides(fill = guide_legend(reverse = TRUE)) for color of area fills (e.g.: box plot Remove the legend title: p + theme(legend.title = element_blank()) . Just specify the argument show.legend = FALSE in the given The configuration of the legend is discussed in detail in the Legends page.. Align Plot Title¶. The following example shows how to align the plot title in layout.title. x sets the x position with respect to xref from "0" (left) to "1" (right), and y sets the y position with respect to yref from "0" (bottom) to "1" (top).
Statistics for Library and Information Services: A Primer for , It lays out the proportion for the ink that is devoted to a nonredundant display of the data of this model is to maximize the proportion of the ink used in the graph that is 17.3.1 SUPPORTING TEXT DESCRIPTION Adding a text description to labels near the data, rather than in a separate legend (e.g., place them on top of Call signatures: legend() legend(labels) legend(handles, labels) The call signatures correspond to three different ways how to use this method. 1. Automatic detection of elements to be shown in the legend. The elements to be added to the legend are automatically determined, when you do not pass in any extra arguments.
Legends (ggplot2), Modifying the appearance of the legend title and labels; Modifying the legend box You can also remove all the legends in a graph, using theme . Modifying the text of legend titles and labels what happens if you just specify colour lp1 + scale_colour_discrete(name ="Payer", fill, Color of area fills (e.g. bar graph). Labels and Annotations. Add a title, label the axes, or add annotations to a graph to help convey important information. You can create a legend to label plotted data series or add descriptive text next to data points. Also, you can create annotations such as rectangles, ellipses, arrows, vertical lines, or horizontal lines that highlight specific areas of data.
- You could set the
0- see e.g. here.
- Thanks @jonrsharpe I had tried code by minimising line and label and overwrite only the label but legend brings both back-> legend = ax.legend(loc=0, shadow=False) for label in legend.get_lines(): label.set_linewidth(0.0) for label in legend.get_texts(): label.set_fontsize(0) ax.legend(loc=0, title='New Title')
- @Java.beginner You should edit your question to include that code. It is un-readable in a comment.
- Hi @tcaswell thanks, I have accepted the answer (second part from 'Joe Kington'). Still you want me edit the question. Thanks
- Yes, so that future uses can understand what you were asking so they can tell if it is the problem they are having
- Thanks @Joe Kington, Have used your second part of the solution. Since I was using dataframe, couldn't force the label name to desired one by default it takes the column name, so have changed the column name according to desired one and font size is too big when I tried to reduce the size -> legend = ax.legend(loc=0, shadow=False)for label in legend.get_texts(): label.set_fontsize(10) -> the it brings back the old legend, is there anyway to fix this, thanks for your time.
- @Java.beginner - That's because you're creating a new legend when you call
legend = ax.legend(...)the second time. If you want to access the first legend, use
- @tsherwen I'm sorry but I don't think this question was specific to a line plot. The title is "How to hide/remove legend line and retain the label" and does not specify that this is intended for a line plot. Also, in theory a line plot can be also created via a scatter plot. Please consider removing the negative marking thanks.