Change the Formatting of labels inside the legend of matplotlib
I want to customize the Legends in matplotlib.
I want to order the labels inside the legends horizontally and remove the handle as well. Color of the labels must be same as the line color.
Currently I have set the handle as invisible, but not able to change the ordering of labels.
Looking forward for expert advice.
Expected output:
What I have achieved so far is the following,
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure(figsize=(10,7))
lines=
lines.append(plt.plot(x, y1, '-b', label='sine')[0])
lines.append(plt.plot(x, y2, '-r', label='cosine')[0])
plt.legend(loc='upper left')
plt.ylim(-1.5, 2.0)
for item_legend,handle,line in zip(plt.legend().get_texts(),plt.gca().get_legend().legendHandles,lines):
plt.setp(item_legend, color=line.get_color(),size=30)
handle.set_visible(False)
plt.show()
output:
Thanks.
EDIT:
If I set
plt.legend(loc='upper left', ncols=2)
Labels are aligned in one row but all the previous formatting gets removed.
python matplotlib
add a comment |
I want to customize the Legends in matplotlib.
I want to order the labels inside the legends horizontally and remove the handle as well. Color of the labels must be same as the line color.
Currently I have set the handle as invisible, but not able to change the ordering of labels.
Looking forward for expert advice.
Expected output:
What I have achieved so far is the following,
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure(figsize=(10,7))
lines=
lines.append(plt.plot(x, y1, '-b', label='sine')[0])
lines.append(plt.plot(x, y2, '-r', label='cosine')[0])
plt.legend(loc='upper left')
plt.ylim(-1.5, 2.0)
for item_legend,handle,line in zip(plt.legend().get_texts(),plt.gca().get_legend().legendHandles,lines):
plt.setp(item_legend, color=line.get_color(),size=30)
handle.set_visible(False)
plt.show()
output:
Thanks.
EDIT:
If I set
plt.legend(loc='upper left', ncols=2)
Labels are aligned in one row but all the previous formatting gets removed.
python matplotlib
add a comment |
I want to customize the Legends in matplotlib.
I want to order the labels inside the legends horizontally and remove the handle as well. Color of the labels must be same as the line color.
Currently I have set the handle as invisible, but not able to change the ordering of labels.
Looking forward for expert advice.
Expected output:
What I have achieved so far is the following,
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure(figsize=(10,7))
lines=
lines.append(plt.plot(x, y1, '-b', label='sine')[0])
lines.append(plt.plot(x, y2, '-r', label='cosine')[0])
plt.legend(loc='upper left')
plt.ylim(-1.5, 2.0)
for item_legend,handle,line in zip(plt.legend().get_texts(),plt.gca().get_legend().legendHandles,lines):
plt.setp(item_legend, color=line.get_color(),size=30)
handle.set_visible(False)
plt.show()
output:
Thanks.
EDIT:
If I set
plt.legend(loc='upper left', ncols=2)
Labels are aligned in one row but all the previous formatting gets removed.
python matplotlib
I want to customize the Legends in matplotlib.
I want to order the labels inside the legends horizontally and remove the handle as well. Color of the labels must be same as the line color.
Currently I have set the handle as invisible, but not able to change the ordering of labels.
Looking forward for expert advice.
Expected output:
What I have achieved so far is the following,
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)
plt.figure(figsize=(10,7))
lines=
lines.append(plt.plot(x, y1, '-b', label='sine')[0])
lines.append(plt.plot(x, y2, '-r', label='cosine')[0])
plt.legend(loc='upper left')
plt.ylim(-1.5, 2.0)
for item_legend,handle,line in zip(plt.legend().get_texts(),plt.gca().get_legend().legendHandles,lines):
plt.setp(item_legend, color=line.get_color(),size=30)
handle.set_visible(False)
plt.show()
output:
Thanks.
EDIT:
If I set
plt.legend(loc='upper left', ncols=2)
Labels are aligned in one row but all the previous formatting gets removed.
python matplotlib
python matplotlib
edited Jan 1 at 16:07
AI_Learning
asked Jan 1 at 15:46
AI_LearningAI_Learning
3,57921033
3,57921033
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
This is how you can do it. The key to left alignment here is to use handletextpad=0
and handlelength=0
. The columnspacing
here controls the horizontal space between the two columns of the legend. Putting the handle length to 0 would simply show the legend texts. You can then finally adapt the color of the legend texts according to the respective curves.
l = plt.legend(loc='upper left', ncol=2, handlelength=0, handletextpad=0, columnspacing=0.5, fontsize=36)
handles = plt.gca().get_legend().legendHandles
for i, text in enumerate(l.get_texts()):
text.set_color(lines[i].get_color())
EDIT (based on the comments)
You can avoid manually specifying the number of columns by using the length of the lines
as ncol
while defining the legend as
l = plt.legend(loc='upper left',ncol=len(lines), handlelength=-0.2, columnspacing=-0.2, fontsize=36)
You can also remove/hide the handle by using the transparency parameter alpha
by setting it to 0 as
handles[i].set_alpha(0)
or by hiding it as
handles[i].set_visible(False)
Thanks @Bazingaa. 1. can we assign n_cols value from some parameter of legends. 2. Is there a better way to remove the handle, instead of making it invisible - guess that's the reason for left alignment problem.
– AI_Learning
Jan 1 at 16:39
1
@AI_Learning: Check my edit in the answer
– Bazingaa
Jan 1 at 17:03
Really hard for me to tell this. transparency = 0 is also similar to set_visible as false. Can we set it None or something so that left alignment works properly.
– AI_Learning
Jan 1 at 17:05
@AI_Learning: I got it. Check my new edit and the corresponding figure
– Bazingaa
Jan 1 at 17:06
1
The key to left alignment here ishandletextpad =0
andhandlelength=0
– Bazingaa
Jan 1 at 17:06
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53996789%2fchange-the-formatting-of-labels-inside-the-legend-of-matplotlib%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
This is how you can do it. The key to left alignment here is to use handletextpad=0
and handlelength=0
. The columnspacing
here controls the horizontal space between the two columns of the legend. Putting the handle length to 0 would simply show the legend texts. You can then finally adapt the color of the legend texts according to the respective curves.
l = plt.legend(loc='upper left', ncol=2, handlelength=0, handletextpad=0, columnspacing=0.5, fontsize=36)
handles = plt.gca().get_legend().legendHandles
for i, text in enumerate(l.get_texts()):
text.set_color(lines[i].get_color())
EDIT (based on the comments)
You can avoid manually specifying the number of columns by using the length of the lines
as ncol
while defining the legend as
l = plt.legend(loc='upper left',ncol=len(lines), handlelength=-0.2, columnspacing=-0.2, fontsize=36)
You can also remove/hide the handle by using the transparency parameter alpha
by setting it to 0 as
handles[i].set_alpha(0)
or by hiding it as
handles[i].set_visible(False)
Thanks @Bazingaa. 1. can we assign n_cols value from some parameter of legends. 2. Is there a better way to remove the handle, instead of making it invisible - guess that's the reason for left alignment problem.
– AI_Learning
Jan 1 at 16:39
1
@AI_Learning: Check my edit in the answer
– Bazingaa
Jan 1 at 17:03
Really hard for me to tell this. transparency = 0 is also similar to set_visible as false. Can we set it None or something so that left alignment works properly.
– AI_Learning
Jan 1 at 17:05
@AI_Learning: I got it. Check my new edit and the corresponding figure
– Bazingaa
Jan 1 at 17:06
1
The key to left alignment here ishandletextpad =0
andhandlelength=0
– Bazingaa
Jan 1 at 17:06
add a comment |
This is how you can do it. The key to left alignment here is to use handletextpad=0
and handlelength=0
. The columnspacing
here controls the horizontal space between the two columns of the legend. Putting the handle length to 0 would simply show the legend texts. You can then finally adapt the color of the legend texts according to the respective curves.
l = plt.legend(loc='upper left', ncol=2, handlelength=0, handletextpad=0, columnspacing=0.5, fontsize=36)
handles = plt.gca().get_legend().legendHandles
for i, text in enumerate(l.get_texts()):
text.set_color(lines[i].get_color())
EDIT (based on the comments)
You can avoid manually specifying the number of columns by using the length of the lines
as ncol
while defining the legend as
l = plt.legend(loc='upper left',ncol=len(lines), handlelength=-0.2, columnspacing=-0.2, fontsize=36)
You can also remove/hide the handle by using the transparency parameter alpha
by setting it to 0 as
handles[i].set_alpha(0)
or by hiding it as
handles[i].set_visible(False)
Thanks @Bazingaa. 1. can we assign n_cols value from some parameter of legends. 2. Is there a better way to remove the handle, instead of making it invisible - guess that's the reason for left alignment problem.
– AI_Learning
Jan 1 at 16:39
1
@AI_Learning: Check my edit in the answer
– Bazingaa
Jan 1 at 17:03
Really hard for me to tell this. transparency = 0 is also similar to set_visible as false. Can we set it None or something so that left alignment works properly.
– AI_Learning
Jan 1 at 17:05
@AI_Learning: I got it. Check my new edit and the corresponding figure
– Bazingaa
Jan 1 at 17:06
1
The key to left alignment here ishandletextpad =0
andhandlelength=0
– Bazingaa
Jan 1 at 17:06
add a comment |
This is how you can do it. The key to left alignment here is to use handletextpad=0
and handlelength=0
. The columnspacing
here controls the horizontal space between the two columns of the legend. Putting the handle length to 0 would simply show the legend texts. You can then finally adapt the color of the legend texts according to the respective curves.
l = plt.legend(loc='upper left', ncol=2, handlelength=0, handletextpad=0, columnspacing=0.5, fontsize=36)
handles = plt.gca().get_legend().legendHandles
for i, text in enumerate(l.get_texts()):
text.set_color(lines[i].get_color())
EDIT (based on the comments)
You can avoid manually specifying the number of columns by using the length of the lines
as ncol
while defining the legend as
l = plt.legend(loc='upper left',ncol=len(lines), handlelength=-0.2, columnspacing=-0.2, fontsize=36)
You can also remove/hide the handle by using the transparency parameter alpha
by setting it to 0 as
handles[i].set_alpha(0)
or by hiding it as
handles[i].set_visible(False)
This is how you can do it. The key to left alignment here is to use handletextpad=0
and handlelength=0
. The columnspacing
here controls the horizontal space between the two columns of the legend. Putting the handle length to 0 would simply show the legend texts. You can then finally adapt the color of the legend texts according to the respective curves.
l = plt.legend(loc='upper left', ncol=2, handlelength=0, handletextpad=0, columnspacing=0.5, fontsize=36)
handles = plt.gca().get_legend().legendHandles
for i, text in enumerate(l.get_texts()):
text.set_color(lines[i].get_color())
EDIT (based on the comments)
You can avoid manually specifying the number of columns by using the length of the lines
as ncol
while defining the legend as
l = plt.legend(loc='upper left',ncol=len(lines), handlelength=-0.2, columnspacing=-0.2, fontsize=36)
You can also remove/hide the handle by using the transparency parameter alpha
by setting it to 0 as
handles[i].set_alpha(0)
or by hiding it as
handles[i].set_visible(False)
edited Jan 1 at 17:05
answered Jan 1 at 16:15
BazingaaBazingaa
15.9k21328
15.9k21328
Thanks @Bazingaa. 1. can we assign n_cols value from some parameter of legends. 2. Is there a better way to remove the handle, instead of making it invisible - guess that's the reason for left alignment problem.
– AI_Learning
Jan 1 at 16:39
1
@AI_Learning: Check my edit in the answer
– Bazingaa
Jan 1 at 17:03
Really hard for me to tell this. transparency = 0 is also similar to set_visible as false. Can we set it None or something so that left alignment works properly.
– AI_Learning
Jan 1 at 17:05
@AI_Learning: I got it. Check my new edit and the corresponding figure
– Bazingaa
Jan 1 at 17:06
1
The key to left alignment here ishandletextpad =0
andhandlelength=0
– Bazingaa
Jan 1 at 17:06
add a comment |
Thanks @Bazingaa. 1. can we assign n_cols value from some parameter of legends. 2. Is there a better way to remove the handle, instead of making it invisible - guess that's the reason for left alignment problem.
– AI_Learning
Jan 1 at 16:39
1
@AI_Learning: Check my edit in the answer
– Bazingaa
Jan 1 at 17:03
Really hard for me to tell this. transparency = 0 is also similar to set_visible as false. Can we set it None or something so that left alignment works properly.
– AI_Learning
Jan 1 at 17:05
@AI_Learning: I got it. Check my new edit and the corresponding figure
– Bazingaa
Jan 1 at 17:06
1
The key to left alignment here ishandletextpad =0
andhandlelength=0
– Bazingaa
Jan 1 at 17:06
Thanks @Bazingaa. 1. can we assign n_cols value from some parameter of legends. 2. Is there a better way to remove the handle, instead of making it invisible - guess that's the reason for left alignment problem.
– AI_Learning
Jan 1 at 16:39
Thanks @Bazingaa. 1. can we assign n_cols value from some parameter of legends. 2. Is there a better way to remove the handle, instead of making it invisible - guess that's the reason for left alignment problem.
– AI_Learning
Jan 1 at 16:39
1
1
@AI_Learning: Check my edit in the answer
– Bazingaa
Jan 1 at 17:03
@AI_Learning: Check my edit in the answer
– Bazingaa
Jan 1 at 17:03
Really hard for me to tell this. transparency = 0 is also similar to set_visible as false. Can we set it None or something so that left alignment works properly.
– AI_Learning
Jan 1 at 17:05
Really hard for me to tell this. transparency = 0 is also similar to set_visible as false. Can we set it None or something so that left alignment works properly.
– AI_Learning
Jan 1 at 17:05
@AI_Learning: I got it. Check my new edit and the corresponding figure
– Bazingaa
Jan 1 at 17:06
@AI_Learning: I got it. Check my new edit and the corresponding figure
– Bazingaa
Jan 1 at 17:06
1
1
The key to left alignment here is
handletextpad =0
and handlelength=0
– Bazingaa
Jan 1 at 17:06
The key to left alignment here is
handletextpad =0
and handlelength=0
– Bazingaa
Jan 1 at 17:06
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53996789%2fchange-the-formatting-of-labels-inside-the-legend-of-matplotlib%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown