Reputation: 435
I have some Pie Charts ploted using Plotly and theirs respective legends. When legends text are short the result is very user friendly (first image), but when legends text are long, the result is not very "professional" (second image).
Here's the code that I'm using to plot the charts:
fig = px.pie(df, values = 'values', names = 'names')
fig.update_layout(title = 'Pie Chart', title_x = 0.5)
fig.show()
Is there any way to truncate or to break the line of the legend text , in order to show the Pie Chart in a better way to the user?
Thx in advance for all your help.
Upvotes: 0
Views: 1059
Reputation: 381
I Think for most use cases, it is much more performant to not change the entire fig
with python but with js:
window.dash_clientside = Object.assign({}, window.dash_clientside, {
clientside: {
trunc_legend_titles: function(figure) {
setTimeout(function() {
var legendItems = document.querySelectorAll('.legendtext');
legendItems.forEach(function(item) {
var name = item.textContent;
var truncatedName = name.length > 10 ? name.substring(0, 10) + '...' : name;
item.textContent = truncatedName;
});
}, 500); // Wait for the plot to be fully rendered
}
}
});
this also does not change the unique name of the underlying data but just the display text in the legend
Upvotes: 0
Reputation: 7769
You can trim the legend name as :
def newLegend(fig):
for i, elem in enumerate(fig.data[0].labels)
fig.data[0].labels[i] = fig.data[0].labels[i][:15] # where 15 is the first 15 letter of the legend
return(fig)
fig = newLegend(fig = fig)
Upvotes: 1