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();
}
);
});
});
yesterday


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
    yesterday










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















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();
}
);
});
});
yesterday


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
    yesterday










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













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 yesterday









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();
}
);
});
});
yesterday


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();
}
);
});
});
yesterday


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
    yesterday










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














  • 2




    Write the text instead of creating a legend?
    – Mr. T
    yesterday










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








2




2




Write the text instead of creating a legend?
– Mr. T
yesterday




Write the text instead of creating a legend?
– Mr. T
yesterday












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




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












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
    yesterday






  • 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
    yesterday










  • 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
    yesterday










  • @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
    yesterday




















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
    yesterday






  • 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
    yesterday










  • 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
    yesterday










  • @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
    yesterday

















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
    yesterday






  • 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
    yesterday










  • 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
    yesterday










  • @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
    yesterday















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 yesterday

























answered yesterday









Srikar

214




214












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






  • 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
    yesterday










  • 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
    yesterday










  • @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
    yesterday




















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






  • 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
    yesterday










  • 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
    yesterday










  • @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
    yesterday


















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




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




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
yesterday




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
yesterday












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
yesterday




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
yesterday












@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
yesterday






@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
yesterday





Popular posts from this blog

Full-time equivalent

Bicuculline

さくらももこ