How to add hatch to custom legend in matplotlib?
up vote
2
down vote
favorite
Edit: FWIW I am fixing the legend in Illustrator, but would prefer to do it automatically because I have about 20 of these plots to make
I followed this very helpful answer for adding a custom legend to a matplotlib violinplot, which doesn't support its own legend. It worked great except when I tried to add hatches.
Here's my code for the labels (I tried adding patch two different ways):
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
legend_patches = 3*[matplotlib.patches.Patch( color='#DCDCDC', hatch='//' )]
for i in legend_patches:
i.set_hatch( '//' )
The code for hatching the violins themselves works fine:
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True )
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for t in range(0, 3):
third = range( 0, len( labels ) )[ t*(int(len(labels)/3)):(((t+1)*int(len(labels)/3))) ]
for i in third:
face = parts['bodies'][i]
face.set_hatch( hatch_dict[t] )
The data the bins relate to (not shown) is already color coded for other categories so I'd really like to show the bins in different hatches.
python matplotlib
add a comment |
up vote
2
down vote
favorite
Edit: FWIW I am fixing the legend in Illustrator, but would prefer to do it automatically because I have about 20 of these plots to make
I followed this very helpful answer for adding a custom legend to a matplotlib violinplot, which doesn't support its own legend. It worked great except when I tried to add hatches.
Here's my code for the labels (I tried adding patch two different ways):
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
legend_patches = 3*[matplotlib.patches.Patch( color='#DCDCDC', hatch='//' )]
for i in legend_patches:
i.set_hatch( '//' )
The code for hatching the violins themselves works fine:
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True )
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for t in range(0, 3):
third = range( 0, len( labels ) )[ t*(int(len(labels)/3)):(((t+1)*int(len(labels)/3))) ]
for i in third:
face = parts['bodies'][i]
face.set_hatch( hatch_dict[t] )
The data the bins relate to (not shown) is already color coded for other categories so I'd really like to show the bins in different hatches.
python matplotlib
add a comment |
up vote
2
down vote
favorite
up vote
2
down vote
favorite
Edit: FWIW I am fixing the legend in Illustrator, but would prefer to do it automatically because I have about 20 of these plots to make
I followed this very helpful answer for adding a custom legend to a matplotlib violinplot, which doesn't support its own legend. It worked great except when I tried to add hatches.
Here's my code for the labels (I tried adding patch two different ways):
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
legend_patches = 3*[matplotlib.patches.Patch( color='#DCDCDC', hatch='//' )]
for i in legend_patches:
i.set_hatch( '//' )
The code for hatching the violins themselves works fine:
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True )
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for t in range(0, 3):
third = range( 0, len( labels ) )[ t*(int(len(labels)/3)):(((t+1)*int(len(labels)/3))) ]
for i in third:
face = parts['bodies'][i]
face.set_hatch( hatch_dict[t] )
The data the bins relate to (not shown) is already color coded for other categories so I'd really like to show the bins in different hatches.
python matplotlib
Edit: FWIW I am fixing the legend in Illustrator, but would prefer to do it automatically because I have about 20 of these plots to make
I followed this very helpful answer for adding a custom legend to a matplotlib violinplot, which doesn't support its own legend. It worked great except when I tried to add hatches.
Here's my code for the labels (I tried adding patch two different ways):
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
legend_patches = 3*[matplotlib.patches.Patch( color='#DCDCDC', hatch='//' )]
for i in legend_patches:
i.set_hatch( '//' )
The code for hatching the violins themselves works fine:
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True )
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for t in range(0, 3):
third = range( 0, len( labels ) )[ t*(int(len(labels)/3)):(((t+1)*int(len(labels)/3))) ]
for i in third:
face = parts['bodies'][i]
face.set_hatch( hatch_dict[t] )
The data the bins relate to (not shown) is already color coded for other categories so I'd really like to show the bins in different hatches.
python matplotlib
python matplotlib
edited Nov 12 at 4:36
asked Nov 12 at 4:18
Amanda
485
485
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
up vote
2
down vote
You are almost there - just need to be careful with the color argument with patches. There are two sub-components: an edge (edgecolor
) and a face (facecolor
); with this patch artist setting the color=
defines both of these colors. The hatch and the background then come out the same color and you can't see one from the other.
Bottom line: use something like this for your patch constructor:
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
Full code for this plot:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches
# generate some data
n = 50
sigmas = np.array([0.1, 0.05, 0.15])
means = np.array([0.2, 0.5, 0.75])
data = sigmas * np.random.randn(n, 3) + means
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True)
# set up color and hatching on the violins
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for i, face in enumerate(parts['bodies']):
face.set_hatch(hatch_dict[i])
face.set_facecolor('#DCDCDC')
# for completeness update all the lines (you already had this styling applied)
for elem in ['cbars', 'cmedians', 'cmaxes', 'cmins']:
parts[elem].set_edgecolor('0.5')
# construct proxy artist patches
leg_artists =
for i in xrange(len(hatch_dict)):
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
# can also explicitly declare 2nd color like this
#p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i], edgecolor='0.5')
leg_artists.append(p)
# and add them to legend.
ax = plt.gca()
ax.legend(leg_artists, labels, loc='upper left')
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',
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%2f53255914%2fhow-to-add-hatch-to-custom-legend-in-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
up vote
2
down vote
You are almost there - just need to be careful with the color argument with patches. There are two sub-components: an edge (edgecolor
) and a face (facecolor
); with this patch artist setting the color=
defines both of these colors. The hatch and the background then come out the same color and you can't see one from the other.
Bottom line: use something like this for your patch constructor:
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
Full code for this plot:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches
# generate some data
n = 50
sigmas = np.array([0.1, 0.05, 0.15])
means = np.array([0.2, 0.5, 0.75])
data = sigmas * np.random.randn(n, 3) + means
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True)
# set up color and hatching on the violins
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for i, face in enumerate(parts['bodies']):
face.set_hatch(hatch_dict[i])
face.set_facecolor('#DCDCDC')
# for completeness update all the lines (you already had this styling applied)
for elem in ['cbars', 'cmedians', 'cmaxes', 'cmins']:
parts[elem].set_edgecolor('0.5')
# construct proxy artist patches
leg_artists =
for i in xrange(len(hatch_dict)):
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
# can also explicitly declare 2nd color like this
#p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i], edgecolor='0.5')
leg_artists.append(p)
# and add them to legend.
ax = plt.gca()
ax.legend(leg_artists, labels, loc='upper left')
add a comment |
up vote
2
down vote
You are almost there - just need to be careful with the color argument with patches. There are two sub-components: an edge (edgecolor
) and a face (facecolor
); with this patch artist setting the color=
defines both of these colors. The hatch and the background then come out the same color and you can't see one from the other.
Bottom line: use something like this for your patch constructor:
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
Full code for this plot:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches
# generate some data
n = 50
sigmas = np.array([0.1, 0.05, 0.15])
means = np.array([0.2, 0.5, 0.75])
data = sigmas * np.random.randn(n, 3) + means
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True)
# set up color and hatching on the violins
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for i, face in enumerate(parts['bodies']):
face.set_hatch(hatch_dict[i])
face.set_facecolor('#DCDCDC')
# for completeness update all the lines (you already had this styling applied)
for elem in ['cbars', 'cmedians', 'cmaxes', 'cmins']:
parts[elem].set_edgecolor('0.5')
# construct proxy artist patches
leg_artists =
for i in xrange(len(hatch_dict)):
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
# can also explicitly declare 2nd color like this
#p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i], edgecolor='0.5')
leg_artists.append(p)
# and add them to legend.
ax = plt.gca()
ax.legend(leg_artists, labels, loc='upper left')
add a comment |
up vote
2
down vote
up vote
2
down vote
You are almost there - just need to be careful with the color argument with patches. There are two sub-components: an edge (edgecolor
) and a face (facecolor
); with this patch artist setting the color=
defines both of these colors. The hatch and the background then come out the same color and you can't see one from the other.
Bottom line: use something like this for your patch constructor:
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
Full code for this plot:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches
# generate some data
n = 50
sigmas = np.array([0.1, 0.05, 0.15])
means = np.array([0.2, 0.5, 0.75])
data = sigmas * np.random.randn(n, 3) + means
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True)
# set up color and hatching on the violins
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for i, face in enumerate(parts['bodies']):
face.set_hatch(hatch_dict[i])
face.set_facecolor('#DCDCDC')
# for completeness update all the lines (you already had this styling applied)
for elem in ['cbars', 'cmedians', 'cmaxes', 'cmins']:
parts[elem].set_edgecolor('0.5')
# construct proxy artist patches
leg_artists =
for i in xrange(len(hatch_dict)):
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
# can also explicitly declare 2nd color like this
#p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i], edgecolor='0.5')
leg_artists.append(p)
# and add them to legend.
ax = plt.gca()
ax.legend(leg_artists, labels, loc='upper left')
You are almost there - just need to be careful with the color argument with patches. There are two sub-components: an edge (edgecolor
) and a face (facecolor
); with this patch artist setting the color=
defines both of these colors. The hatch and the background then come out the same color and you can't see one from the other.
Bottom line: use something like this for your patch constructor:
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
Full code for this plot:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches
# generate some data
n = 50
sigmas = np.array([0.1, 0.05, 0.15])
means = np.array([0.2, 0.5, 0.75])
data = sigmas * np.random.randn(n, 3) + means
labels = [ 'Low entropy bin', 'Medium entropy bin', 'High entropy bin' ]
parts = plt.violinplot( data, showmeans=False, showextrema=True, showmedians=True)
# set up color and hatching on the violins
hatch_dict = { 0:'', 1:'///', 2:'xx' }
for i, face in enumerate(parts['bodies']):
face.set_hatch(hatch_dict[i])
face.set_facecolor('#DCDCDC')
# for completeness update all the lines (you already had this styling applied)
for elem in ['cbars', 'cmedians', 'cmaxes', 'cmins']:
parts[elem].set_edgecolor('0.5')
# construct proxy artist patches
leg_artists =
for i in xrange(len(hatch_dict)):
p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i])
# can also explicitly declare 2nd color like this
#p = matplotlib.patches.Patch(facecolor='#DCDCDC', hatch=hatch_dict[i], edgecolor='0.5')
leg_artists.append(p)
# and add them to legend.
ax = plt.gca()
ax.legend(leg_artists, labels, loc='upper left')
answered Nov 12 at 11:15
Bonlenfum
11k13041
11k13041
add a comment |
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.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- 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%2f53255914%2fhow-to-add-hatch-to-custom-legend-in-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