python matplotlib custom legend [duplicate]









up vote
1
down vote

favorite













This question already has an answer here:



  • Remove legend key in matplotlib

    1 answer



I am using python to stream and plot some sensor data from an arduino to my pc.
I want the graph to have a legend with some values (that I also stream from my serial connection of course) but in all examples I found there was a big space at the left side of the legend.



How can I remove it? (Or get the same output using something else)



This is my code:



#!/usr/bin/python

import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline
import matplotlib.patches as mpatches

# Local variables
x =
y =

# Open the data file for reading lines
datafile = open('./plotfiles/forceplot.txt', 'r')
sepfile = datafile.read().split('n')
datafile.close()

# Create a canvas to place the subgraphs
canvas = plt.figure()
rect = canvas.patch
rect.set_facecolor('white')

# Iterate through the lines and parse them
for datapair in sepfile:
if datapair:
xypair = datapair.split(',')
x.append(int(xypair[0]))
y.append(int(xypair[1]))

x_sm = np.array(x)
y_sm = np.array(y)

x_smooth = np.linspace(x_sm.min(), x_sm.max(), 200)
y_smooth = spline(x, y, x_smooth)

# Define the matrix of 1x1 to place subplots
# Placing the plot1 on 1x1 matrix, at pos 1
sp1 = canvas.add_subplot(1,1,1)
#sp1.plot(x, y, 'red', linewidth=2)
sp1.plot(x_smooth, y_smooth, 'red', linewidth=1)

# Colorcode the tick tabs
sp1.tick_params(axis='x', colors='red')
sp1.tick_params(axis='y', colors='red')

# Colorcode the spine of the graph
sp1.spines['bottom'].set_color('r')
sp1.spines['top'].set_color('r')
sp1.spines['left'].set_color('r')
sp1.spines['right'].set_color('r')

# Put the title and labels
sp1.set_title('matplotlib example 1', color='red')
sp1.set_xlabel('matplot x label', color='red')
sp1.set_ylabel('matplot y label', color='red')

# Show the plot/image
time = 'time: 00:23'
s = 3
sh = "success hits: "+str(s)
legend_dict = sh: sh, 'total hits' : '5', time : time
patchList=
for key in legend_dict:
data_key = mpatches.Patch(color='None', label=key)
patchList.append(data_key)

plt.legend(handles=patchList)

plt.tight_layout()
plt.grid(alpha=0.8)
plt.savefig("example6.eps")
plt.show()


And this is the output:



enter image description here










share|improve this question













marked as duplicate by ImportanceOfBeingErnest matplotlib
Users with the  matplotlib badge can single-handedly close matplotlib questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 2




    Write the text instead of creating a legend?
    – Mr. T
    2 days ago










  • @Mr.T Ok but how can I autoscale the coordinates of the text?
    – George Sp
    2 days ago














up vote
1
down vote

favorite













This question already has an answer here:



  • Remove legend key in matplotlib

    1 answer



I am using python to stream and plot some sensor data from an arduino to my pc.
I want the graph to have a legend with some values (that I also stream from my serial connection of course) but in all examples I found there was a big space at the left side of the legend.



How can I remove it? (Or get the same output using something else)



This is my code:



#!/usr/bin/python

import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline
import matplotlib.patches as mpatches

# Local variables
x =
y =

# Open the data file for reading lines
datafile = open('./plotfiles/forceplot.txt', 'r')
sepfile = datafile.read().split('n')
datafile.close()

# Create a canvas to place the subgraphs
canvas = plt.figure()
rect = canvas.patch
rect.set_facecolor('white')

# Iterate through the lines and parse them
for datapair in sepfile:
if datapair:
xypair = datapair.split(',')
x.append(int(xypair[0]))
y.append(int(xypair[1]))

x_sm = np.array(x)
y_sm = np.array(y)

x_smooth = np.linspace(x_sm.min(), x_sm.max(), 200)
y_smooth = spline(x, y, x_smooth)

# Define the matrix of 1x1 to place subplots
# Placing the plot1 on 1x1 matrix, at pos 1
sp1 = canvas.add_subplot(1,1,1)
#sp1.plot(x, y, 'red', linewidth=2)
sp1.plot(x_smooth, y_smooth, 'red', linewidth=1)

# Colorcode the tick tabs
sp1.tick_params(axis='x', colors='red')
sp1.tick_params(axis='y', colors='red')

# Colorcode the spine of the graph
sp1.spines['bottom'].set_color('r')
sp1.spines['top'].set_color('r')
sp1.spines['left'].set_color('r')
sp1.spines['right'].set_color('r')

# Put the title and labels
sp1.set_title('matplotlib example 1', color='red')
sp1.set_xlabel('matplot x label', color='red')
sp1.set_ylabel('matplot y label', color='red')

# Show the plot/image
time = 'time: 00:23'
s = 3
sh = "success hits: "+str(s)
legend_dict = sh: sh, 'total hits' : '5', time : time
patchList=
for key in legend_dict:
data_key = mpatches.Patch(color='None', label=key)
patchList.append(data_key)

plt.legend(handles=patchList)

plt.tight_layout()
plt.grid(alpha=0.8)
plt.savefig("example6.eps")
plt.show()


And this is the output:



enter image description here










share|improve this question













marked as duplicate by ImportanceOfBeingErnest matplotlib
Users with the  matplotlib badge can single-handedly close matplotlib questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 2




    Write the text instead of creating a legend?
    – Mr. T
    2 days ago










  • @Mr.T Ok but how can I autoscale the coordinates of the text?
    – George Sp
    2 days ago












up vote
1
down vote

favorite









up vote
1
down vote

favorite












This question already has an answer here:



  • Remove legend key in matplotlib

    1 answer



I am using python to stream and plot some sensor data from an arduino to my pc.
I want the graph to have a legend with some values (that I also stream from my serial connection of course) but in all examples I found there was a big space at the left side of the legend.



How can I remove it? (Or get the same output using something else)



This is my code:



#!/usr/bin/python

import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline
import matplotlib.patches as mpatches

# Local variables
x =
y =

# Open the data file for reading lines
datafile = open('./plotfiles/forceplot.txt', 'r')
sepfile = datafile.read().split('n')
datafile.close()

# Create a canvas to place the subgraphs
canvas = plt.figure()
rect = canvas.patch
rect.set_facecolor('white')

# Iterate through the lines and parse them
for datapair in sepfile:
if datapair:
xypair = datapair.split(',')
x.append(int(xypair[0]))
y.append(int(xypair[1]))

x_sm = np.array(x)
y_sm = np.array(y)

x_smooth = np.linspace(x_sm.min(), x_sm.max(), 200)
y_smooth = spline(x, y, x_smooth)

# Define the matrix of 1x1 to place subplots
# Placing the plot1 on 1x1 matrix, at pos 1
sp1 = canvas.add_subplot(1,1,1)
#sp1.plot(x, y, 'red', linewidth=2)
sp1.plot(x_smooth, y_smooth, 'red', linewidth=1)

# Colorcode the tick tabs
sp1.tick_params(axis='x', colors='red')
sp1.tick_params(axis='y', colors='red')

# Colorcode the spine of the graph
sp1.spines['bottom'].set_color('r')
sp1.spines['top'].set_color('r')
sp1.spines['left'].set_color('r')
sp1.spines['right'].set_color('r')

# Put the title and labels
sp1.set_title('matplotlib example 1', color='red')
sp1.set_xlabel('matplot x label', color='red')
sp1.set_ylabel('matplot y label', color='red')

# Show the plot/image
time = 'time: 00:23'
s = 3
sh = "success hits: "+str(s)
legend_dict = sh: sh, 'total hits' : '5', time : time
patchList=
for key in legend_dict:
data_key = mpatches.Patch(color='None', label=key)
patchList.append(data_key)

plt.legend(handles=patchList)

plt.tight_layout()
plt.grid(alpha=0.8)
plt.savefig("example6.eps")
plt.show()


And this is the output:



enter image description here










share|improve this question














This question already has an answer here:



  • Remove legend key in matplotlib

    1 answer



I am using python to stream and plot some sensor data from an arduino to my pc.
I want the graph to have a legend with some values (that I also stream from my serial connection of course) but in all examples I found there was a big space at the left side of the legend.



How can I remove it? (Or get the same output using something else)



This is my code:



#!/usr/bin/python

import matplotlib.pyplot as plt
import time
import numpy as np
from scipy.interpolate import spline
import matplotlib.patches as mpatches

# Local variables
x =
y =

# Open the data file for reading lines
datafile = open('./plotfiles/forceplot.txt', 'r')
sepfile = datafile.read().split('n')
datafile.close()

# Create a canvas to place the subgraphs
canvas = plt.figure()
rect = canvas.patch
rect.set_facecolor('white')

# Iterate through the lines and parse them
for datapair in sepfile:
if datapair:
xypair = datapair.split(',')
x.append(int(xypair[0]))
y.append(int(xypair[1]))

x_sm = np.array(x)
y_sm = np.array(y)

x_smooth = np.linspace(x_sm.min(), x_sm.max(), 200)
y_smooth = spline(x, y, x_smooth)

# Define the matrix of 1x1 to place subplots
# Placing the plot1 on 1x1 matrix, at pos 1
sp1 = canvas.add_subplot(1,1,1)
#sp1.plot(x, y, 'red', linewidth=2)
sp1.plot(x_smooth, y_smooth, 'red', linewidth=1)

# Colorcode the tick tabs
sp1.tick_params(axis='x', colors='red')
sp1.tick_params(axis='y', colors='red')

# Colorcode the spine of the graph
sp1.spines['bottom'].set_color('r')
sp1.spines['top'].set_color('r')
sp1.spines['left'].set_color('r')
sp1.spines['right'].set_color('r')

# Put the title and labels
sp1.set_title('matplotlib example 1', color='red')
sp1.set_xlabel('matplot x label', color='red')
sp1.set_ylabel('matplot y label', color='red')

# Show the plot/image
time = 'time: 00:23'
s = 3
sh = "success hits: "+str(s)
legend_dict = sh: sh, 'total hits' : '5', time : time
patchList=
for key in legend_dict:
data_key = mpatches.Patch(color='None', label=key)
patchList.append(data_key)

plt.legend(handles=patchList)

plt.tight_layout()
plt.grid(alpha=0.8)
plt.savefig("example6.eps")
plt.show()


And this is the output:



enter image description here





This question already has an answer here:



  • Remove legend key in matplotlib

    1 answer







python python-3.x matplotlib legend






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









George Sp

10210




10210




marked as duplicate by ImportanceOfBeingErnest matplotlib
Users with the  matplotlib badge can single-handedly close matplotlib questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






marked as duplicate by ImportanceOfBeingErnest matplotlib
Users with the  matplotlib badge can single-handedly close matplotlib questions as duplicates and reopen them as needed.

StackExchange.ready(function()
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();

);
);
);
2 days ago


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









  • 2




    Write the text instead of creating a legend?
    – Mr. T
    2 days ago










  • @Mr.T Ok but how can I autoscale the coordinates of the text?
    – George Sp
    2 days ago












  • 2




    Write the text instead of creating a legend?
    – Mr. T
    2 days ago










  • @Mr.T Ok but how can I autoscale the coordinates of the text?
    – George Sp
    2 days ago







2




2




Write the text instead of creating a legend?
– Mr. T
2 days ago




Write the text instead of creating a legend?
– Mr. T
2 days ago












@Mr.T Ok but how can I autoscale the coordinates of the text?
– George Sp
2 days ago




@Mr.T Ok but how can I autoscale the coordinates of the text?
– George Sp
2 days ago












1 Answer
1






active

oldest

votes

















up vote
0
down vote













Since the color is None, it displays empty space. If you use text:



text(x, y,'time: 00:23nsuccess hits: 3ntotal hits: 5', horizontalalignment='center',
verticalalignment='center')






share|improve this answer






















  • Your x and y would be 1 and 1 as you want it on top right.
    – Srikar
    2 days ago






  • 2




    So, after reading my comment you fundamentally changed your answer and copied the suggestion from the linked answer? This is not how SO is supposed to work.
    – Mr. T
    2 days ago










  • I did change my answer as I had did not read his complete code, but I never referred to your link. I got that text from my previous codes.
    – Srikar
    2 days ago










  • @Srikar T And what can I do for autoscale? My figure has autoscale and when the graph increases in x axe or the figure window gets changed my text is hidden or get's close to the middle of the graph
    – George Sp
    2 days ago











  • Try using anchored text instead of the normal one. From mpl_toolkits use the AnchoredText. txt = AnchoredText("YOUR TEXT",loc=1), ax.add_artist(txt)
    – Srikar
    21 hours ago


















1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote













Since the color is None, it displays empty space. If you use text:



text(x, y,'time: 00:23nsuccess hits: 3ntotal hits: 5', horizontalalignment='center',
verticalalignment='center')






share|improve this answer






















  • Your x and y would be 1 and 1 as you want it on top right.
    – Srikar
    2 days ago






  • 2




    So, after reading my comment you fundamentally changed your answer and copied the suggestion from the linked answer? This is not how SO is supposed to work.
    – Mr. T
    2 days ago










  • I did change my answer as I had did not read his complete code, but I never referred to your link. I got that text from my previous codes.
    – Srikar
    2 days ago










  • @Srikar T And what can I do for autoscale? My figure has autoscale and when the graph increases in x axe or the figure window gets changed my text is hidden or get's close to the middle of the graph
    – George Sp
    2 days ago











  • Try using anchored text instead of the normal one. From mpl_toolkits use the AnchoredText. txt = AnchoredText("YOUR TEXT",loc=1), ax.add_artist(txt)
    – Srikar
    21 hours ago















up vote
0
down vote













Since the color is None, it displays empty space. If you use text:



text(x, y,'time: 00:23nsuccess hits: 3ntotal hits: 5', horizontalalignment='center',
verticalalignment='center')






share|improve this answer






















  • Your x and y would be 1 and 1 as you want it on top right.
    – Srikar
    2 days ago






  • 2




    So, after reading my comment you fundamentally changed your answer and copied the suggestion from the linked answer? This is not how SO is supposed to work.
    – Mr. T
    2 days ago










  • I did change my answer as I had did not read his complete code, but I never referred to your link. I got that text from my previous codes.
    – Srikar
    2 days ago










  • @Srikar T And what can I do for autoscale? My figure has autoscale and when the graph increases in x axe or the figure window gets changed my text is hidden or get's close to the middle of the graph
    – George Sp
    2 days ago











  • Try using anchored text instead of the normal one. From mpl_toolkits use the AnchoredText. txt = AnchoredText("YOUR TEXT",loc=1), ax.add_artist(txt)
    – Srikar
    21 hours ago













up vote
0
down vote










up vote
0
down vote









Since the color is None, it displays empty space. If you use text:



text(x, y,'time: 00:23nsuccess hits: 3ntotal hits: 5', horizontalalignment='center',
verticalalignment='center')






share|improve this answer














Since the color is None, it displays empty space. If you use text:



text(x, y,'time: 00:23nsuccess hits: 3ntotal hits: 5', horizontalalignment='center',
verticalalignment='center')







share|improve this answer














share|improve this answer



share|improve this answer








edited 2 days ago

























answered 2 days ago









Srikar

214




214











  • Your x and y would be 1 and 1 as you want it on top right.
    – Srikar
    2 days ago






  • 2




    So, after reading my comment you fundamentally changed your answer and copied the suggestion from the linked answer? This is not how SO is supposed to work.
    – Mr. T
    2 days ago










  • I did change my answer as I had did not read his complete code, but I never referred to your link. I got that text from my previous codes.
    – Srikar
    2 days ago










  • @Srikar T And what can I do for autoscale? My figure has autoscale and when the graph increases in x axe or the figure window gets changed my text is hidden or get's close to the middle of the graph
    – George Sp
    2 days ago











  • Try using anchored text instead of the normal one. From mpl_toolkits use the AnchoredText. txt = AnchoredText("YOUR TEXT",loc=1), ax.add_artist(txt)
    – Srikar
    21 hours ago

















  • Your x and y would be 1 and 1 as you want it on top right.
    – Srikar
    2 days ago






  • 2




    So, after reading my comment you fundamentally changed your answer and copied the suggestion from the linked answer? This is not how SO is supposed to work.
    – Mr. T
    2 days ago










  • I did change my answer as I had did not read his complete code, but I never referred to your link. I got that text from my previous codes.
    – Srikar
    2 days ago










  • @Srikar T And what can I do for autoscale? My figure has autoscale and when the graph increases in x axe or the figure window gets changed my text is hidden or get's close to the middle of the graph
    – George Sp
    2 days ago











  • Try using anchored text instead of the normal one. From mpl_toolkits use the AnchoredText. txt = AnchoredText("YOUR TEXT",loc=1), ax.add_artist(txt)
    – Srikar
    21 hours ago
















Your x and y would be 1 and 1 as you want it on top right.
– Srikar
2 days ago




Your x and y would be 1 and 1 as you want it on top right.
– Srikar
2 days ago




2




2




So, after reading my comment you fundamentally changed your answer and copied the suggestion from the linked answer? This is not how SO is supposed to work.
– Mr. T
2 days ago




So, after reading my comment you fundamentally changed your answer and copied the suggestion from the linked answer? This is not how SO is supposed to work.
– Mr. T
2 days ago












I did change my answer as I had did not read his complete code, but I never referred to your link. I got that text from my previous codes.
– Srikar
2 days ago




I did change my answer as I had did not read his complete code, but I never referred to your link. I got that text from my previous codes.
– Srikar
2 days ago












@Srikar T And what can I do for autoscale? My figure has autoscale and when the graph increases in x axe or the figure window gets changed my text is hidden or get's close to the middle of the graph
– George Sp
2 days ago





@Srikar T And what can I do for autoscale? My figure has autoscale and when the graph increases in x axe or the figure window gets changed my text is hidden or get's close to the middle of the graph
– George Sp
2 days ago













Try using anchored text instead of the normal one. From mpl_toolkits use the AnchoredText. txt = AnchoredText("YOUR TEXT",loc=1), ax.add_artist(txt)
– Srikar
21 hours ago





Try using anchored text instead of the normal one. From mpl_toolkits use the AnchoredText. txt = AnchoredText("YOUR TEXT",loc=1), ax.add_artist(txt)
– Srikar
21 hours ago




這個網誌中的熱門文章

Barbados

How to read a connectionString WITH PROVIDER in .NET Core?

Node.js Script on GitHub Pages or Amazon S3