I have a plotly graph that uses the Dash library to manipulate the x-values on the plot for simple comparison. When x values, in this case countries, is greater than 1, the legend is properly positioned outside of the graph. However, when there is only one country on the plot, the legend covers half of the plot.
I have tried: setting the legend x attribute to 3, x anchor to right, and changing the graph margin to add padding. I haven't found a solution that works.
Below is the section of the code that updates the plotly fig.
window_width = 1500
fig = px.bar(data_frame=dfi5.loc[(value_country)], width=(window_width / 4) * len(value_country))
fig.update_xaxes(showticklabels=True, title='')
fig.update_yaxes(showticklabels=True, title='Percent of Respondents')
fig.update_layout(autosize=False, title_text='Favorite K-Drama by Country', title_x=.46, title_font_size=20,
legend_title_text='Drama Title', margin_r=1, legend_xanchor='right', legend_x=3, legend_itemsizing='constant')
Update: I was able to find a workaround by reducing the legend font size, which reduces the area of the legend. I would be interested to learn if there is a way to explicitly set the location of the legend. The issue seems to occur when the legend area is wider than the plot area.
Related
I am using plotly (python) in Dash to create a bar plot. I want to set the absolute height of the yaxis (not the full plot).
So each bar should have a maximum height of x pixels and the whole plot area including the tick labels can expand as necessary for the labels.
Is this possible?
figure explaining desired height
I'm having trouble with the location of the bars on the scale. I understand it to be that some of the hue amounts are 0, so this is throwing off the position of the bars. In the image, the top right plot shows the green and brown bars for 'labour' with a gap between, presumably because that color is 0. Is there a way to put the bars together, and in line with their correspondence on the y-axis?
grid = sns.catplot(x='Type', y='count',
row='Age', col='Gender',
hue='Nationality',
data=dfNorthumbria2, kind='bar', ci=None,legend=True)
grid.set(ylim=(0,5), yticks=[0,1,2,3,4,5])
grid.set(xlabel="Type of Exploitation",ylabel="Total Referrals")
for ax in grid.axes.flatten():
ax.tick_params(labelbottom=True, rotation=90)
ax.tick_params(labelleft=True)
grid.fig.tight_layout()
leg = grid._legend
leg.set_bbox_to_anchor([1.1,0.5])
You can pass a hue_order argument to sns.barplot() via sns.catplot, e.g.
grid = sns.catplot(..., hue_order=['British', 'Romanian', 'Vietnamese',
'Albanian', 'Pakistani', 'Slovak'])
This should close the gap between the green and brown bars, and they will be centered at the tick mark, as they are now in the middle of the list. However, groups of other bars will still not be centered around their tick mark.
This may be an unavoidable consequence of how this plotting function works, it's not designed for such sparse data. So if you want all the different groups of bars to be centered at their respective tick marks, you may have to use a more flexible matplotlib plotting function and create the color subsets manually.
Using matplotlib in python. The legend overlaps with my pie chart. Tried various options for "loc" such as "best" ,1,2,3... but to no avail. Any Suggestions as to how to either exactly mention the legend position (such as giving padding from the pie chart boundaries) or at least make sure that it does not overlap?
The short answer is: You may use plt.legend's arguments loc, bbox_to_anchor and additionally bbox_transform and mode, to position the legend in an axes or figure.
The long version:
Step 1: Making sure a legend is needed.
In many cases no legend is needed at all and the information can be inferred by the context or the color directly:
If indeed the plot cannot live without a legend, proceed to step 2.
Step 2: Making sure, a pie chart is needed.
In many cases pie charts are not the best way to convey information.
If the need for a pie chart is unambiguously determined, let's proceed to place the legend.
Placing the legend
plt.legend() has two main arguments to determine the position of the legend. The most important and in itself sufficient is the loc argument.
E.g. plt.legend(loc="upper left") placed the legend such that it sits in the upper left corner of its bounding box. If no further argument is specified, this bounding box will be the entire axes.
However, we may specify our own bounding box using the bbox_to_anchor argument. If bbox_to_anchor is given a 2-tuple e.g. bbox_to_anchor=(1,1) it means that the bounding box is located at the upper right corner of the axes and has no extent. It then acts as a point relative to which the legend will be placed according to the loc argument. It will then expand out of the zero-size bounding box. E.g. if loc is "upper left", the upper left corner of the legend is at position (1,1) and the legend will expand to the right and downwards.
This concept is used for the above plot, which tells us the shocking truth about the bias in Miss Universe elections.
import matplotlib.pyplot as plt
import matplotlib.patches
total = [100]
labels = ["Earth", "Mercury", "Venus", "Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto *"]
plt.title('Origin of Miss Universe since 1952')
plt.gca().axis("equal")
pie = plt.pie(total, startangle=90, colors=[plt.cm.Set3(0)],
wedgeprops = { 'linewidth': 2, "edgecolor" :"k" })
handles = []
for i, l in enumerate(labels):
handles.append(matplotlib.patches.Patch(color=plt.cm.Set3((i)/8.), label=l))
plt.legend(handles,labels, bbox_to_anchor=(0.85,1.025), loc="upper left")
plt.gcf().text(0.93,0.04,"* out of competition since 2006", ha="right")
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.75)
In order for the legend not to exceed the figure, we use plt.subplots_adjust to obtain more space between the figure edge and the axis, which can then be taken up by the legend.
There is also the option to use a 4-tuple to bbox_to_anchor. How to use or interprete this is detailed in this question: What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?
and one may then use the mode="expand" argument to make the legend fit into the specified bounding box.
There are some useful alternatives to this approach:
Using figure coordinates
Instead of specifying the legend position in axes coordinates, one may use figure coordinates. The advantage is that this will allow to simply place the legend in one corner of the figure without adjusting much of the rest. To this end, one would use the bbox_transform argument and supply the figure transformation to it. The coordinates given to bbox_to_anchor are then interpreted as figure coordinates.
plt.legend(pie[0],labels, bbox_to_anchor=(1,0), loc="lower right",
bbox_transform=plt.gcf().transFigure)
Here (1,0) is the lower right corner of the figure. Because of the default spacings between axes and figure edge, this suffices to place the legend such that it does not overlap with the pie.
In other cases, one might still need to adapt those spacings such that no overlap is seen, e.g.
title = plt.title('What slows down my computer')
title.set_ha("left")
plt.gca().axis("equal")
pie = plt.pie(total, startangle=0)
labels=["Trojans", "Viruses", "Too many open tabs", "The anti-virus software"]
plt.legend(pie[0],labels, bbox_to_anchor=(1,0.5), loc="center right", fontsize=10,
bbox_transform=plt.gcf().transFigure)
plt.subplots_adjust(left=0.0, bottom=0.1, right=0.45)
Saving the file with bbox_inches="tight"
Now there may be cases where we are more interested in the saved figure than at what is shown on the screen. We may then simply position the legend at the edge of the figure, like so
but then save it using the bbox_inches="tight" to savefig,
plt.savefig("output.png", bbox_inches="tight")
This will create a larger figure, which sits tight around the contents of the canvas:
A sophisticated approach, which allows to place the legend tightly inside the figure, without changing the figure size is presented here:
Creating figure with exact size and no padding (and legend outside the axes)
Using Subplots
An alternative is to use subplots to reserve space for the legend. In this case one subplot could take the pie chart, another subplot would contain the legend. This is shown below.
fig = plt.figure(4, figsize=(3,3))
ax = fig.add_subplot(211)
total = [4,3,2,81]
labels = ["tough working conditions", "high risk of accident",
"harsh weather", "it's not allowed to watch DVDs"]
ax.set_title('What people know about oil rigs')
ax.axis("equal")
pie = ax.pie(total, startangle=0)
ax2 = fig.add_subplot(212)
ax2.axis("off")
ax2.legend(pie[0],labels, loc="center")
I have 2 subplots in matplotlib in Python. They are stacked on top of each other.
I want to have gridlines on each plot, which I have done successfully. But each plot has a different x axis and, therefore, the vertical grid lines of the top plot are not aligned with those of the bottom plot.
I would like the grid lines of the top plot to be in the same position on the x axis as they are on the bottom plot i.e. the vertical grid lines in both plots should be aligned.
I imaging that I can tell my grid lines exactly where to be, and so I could achieve my goal by adjusting the lines until they match as well as possible.
I just hoped that there might be some easier way that would just allow me to align the gridlines on both plots.
Edit:
I don't think the shared axis stuff is quite what I want.
My top and bottom plot have very different scales, so when I share the axes, it shifts the scaling too. For example, say my top plot has data that runs from 0-100 on the x axis and on the bottom plot the data runs from 0-50. When I share the axis, the top plot only shows data from 0-50, which I don't want it to.
I want it to show from 0-100 as it did before, but just want it to share the axis and gridlines from the other plot.
You could use LinearLocator:
from matplotlib.ticker import LinearLocator
Then on each of your x-axis or only on one of them call:
N = 6 # Set number of gridlines you want to have in each graph
ax1.xaxis.set_major_locator(LinearLocator(N))
ax2.xaxis.set_major_locator(LinearLocator(N))
Or get the number of ticks from your source axis and set it on target axis:
N = source_ax.xaxis.get_major_ticks()
target_ax.xaxis.set_major_locator(LinearLocator(N))
I am plotting a 2D view of a spacecraft orbit using matplotlib. On this orbit, I identify and mark certain events, and then list these events and the corresponding dates in a legend. Before saving the figure to a file, I autozoom on my orbit plot, which causes the legend to be printed directly on top of my plot. What I would like to do is, after autoscaling, somehow find out the width of my legend, and then expand my xaxis to "make room" for the legend on the right side of the plot. Conceptually, something like this;
# ... code that generates my plot up here, then:
ax.autoscale_view()
leg = ax.get_legend()
leg_width = # Somehow get the width of legend in units that I can use to modify my axes
xlims = ax.get_xlim()
ax.set_xlim( [xlims[0], xlims[1] + leg_width] )
fig.savefig('myplot.ps',format='ps')
The main problem I'm having is that ax.set_xlim() takes "data" specific values, whereas leg.get_window_extent reports in window pixels (I think), and even that only after the canvas has been drawn, so I'm not sure how I can get the legend "width" in a way that I can use similar to above.
You can save the figure once to get the real legend location, and then use transData.inverted() to transform screen coordinate to data coordinate.
import pylab as pl
ax = pl.subplot(111)
pl.plot(pl.randn(1000), pl.randn(1000), label="ok")
leg = pl.legend()
pl.savefig("test.png") # save once to get the legend location
x,y,w,h = leg.get_window_extent().bounds
# transform from screen coordinate to screen coordinate
tmp1, tmp2 = ax.transData.inverted().transform([0, w])
print abs(tmp1-tmp2) # this is the with of legend in data coordinate
pl.savefig("test.png")