axes and labeling not in plot white area - matplotlib

I am trying to make a plot in a Colaboratory notebook. I am using following code:
# Plot data
rcParams.update({'figure.autolayout': True})
plt.figure(figsize=(12,8))
plt.title("Charleston", size=24)
plt.xlabel("Year", size=20)
plt.ylabel("High Tide Floods (days/year)", size=20)
plt.plot(HTF_yr.index, HTF_yr.numdays, color='black',marker ='o')
plt.show()
Result (below) displays axes and labels in a grey area. How do I include them in the white area, i.e. the figure itself?

Related

How do I stretch our the horizontal axis of a matplotlib pyplot?

I'm creating a colour map which has 64 horizontal data points and 3072 vertical. When I plot it, the scaling on both axes is the same and so the horizontal axis is super squished and tiny, and I can't get any information from it. I've tried changing the figsize parameter but nothing changes the actual plot, only the image that contains it. Any ideas on how to change my plot so that the actual length of the axes are the same? Below is my plotting code:
def plot_plot(self, data, title="Pixel Plot"):
pixel_plot = plt.imshow(data)
plt.title(title)
plt.colorbar(pixel_plot)
plt.show(pixel_plot)
thanks in advance!
I think you want the aspect option in plt.imshow().
So something like plt.imshow(data, aspect=0.1) or plt.imshow(data, aspect='equal')
See this solution: https://stackoverflow.com/a/13390798/12133280

Seaborn legend modification for multiple overlapping plots

I am trying to create a seaborn boxplot and overlay with individual data points using seaborn swarmplot for a dataset that has two categorical variables (Nameplate Capacity and Scenario) and one continuous variable (ELCC values). Since I have two overlaying plots in seaborn, it is generating two legends for the same variables being plotted. How do I plot a box plot along with a swarm plot while only showing the legend from the box plot. My current code looks like:
plt.subplots(figsize=(25,18))
sns.set_theme(style = "whitegrid", font_scale= 1.5 )
ax = sns.boxplot(x="Scenario", y="ELCC", hue = "Nameplate Capacity",
data=final_offshore, palette = "Pastel1")
ax = sns.swarmplot(x="Scenario", y="ELCC", hue = "Nameplate Capacity", dodge=True, marker='D', size =9, alpha=0.35, data=final_offshore, color="black")
plt.xlabel('Scenarios')
plt.ylabel('ELCC values')
plt.title('Contribution of ad-hoc offshore generator in each scenario')
My plot so far:
You can draw your box plot, get that legend, draw the swarm plot and then re-draw the legend:
# Draw the bar chart
ax = sns.boxplot(
x="Scenario",
y="ELCC",
hue="Nameplate Capacity",
data=final_offshore,
palette="Pastel1",
)
# Get the legend from just the box plot
handles, labels = ax.get_legend_handles_labels()
# Draw the swarmplot
sns.swarmplot(
x="Scenario",
y="ELCC",
hue="Nameplate Capacity",
dodge=True,
marker="D",
size=9,
alpha=0.35,
data=final_offshore,
color="black",
ax=ax,
)
# Remove the old legend
ax.legend_.remove()
# Add just the handles/labels from the box plot back
ax.legend(
handles,
labels,
loc=0,
)

autofmt_xdate() not drawing the label diagonally

I was using jupyterlab to create a graph for highest daily temperature. This is the part of my code that does the graphing. I tried to use 'autofmt_xdate()' attribute to draw the date labels diagonally, but it doesn't work. The date labels were still drawn horizontally, overlapping each other.
from matplotlib import pyplot as plt
fig=plt.figure(dpi=128,figsize=(10,6))
plt.show()
plt.plot(dates,highs,c='Red')
plt.title('highest temperature,July 2018')
plt.xlabel('date',fontsize=16)
fig.autofmt_xdate()
plt.ylabel('temperature C',fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()

How to overlay one pyplot figure on another

Searching easily reveals how to plot multiple charts on one figure, whether using the same plotting axes, a second y axis or subplots. Much harder to uncover is how to overlay one figure onto another, something like this:
That image was prepared using a bitmap editor to overlay the images. I have no difficulty creating the individual plots, but cannot figure out how to combine them. I expect a single line of code will suffice, but what is it? Here is how I imagine it:
bigFig = plt.figure(1, figsize=[5,25])
...
ltlFig = plt.figure(2)
...
bigFig.overlay(ltlFig, pos=[x,y], size=[1,1])
I've established that I can use figure.add_axes, but it is quite challenging getting the position of the overlaid plot correct, since the parameters are fractions, not x,y values from the first plot. It also [it seems to me - am I wrong?] places constraints on the order in which the charts are plotted, since the main plot must be completed before the other plots are added in turn.
What is the pyplot method that achieves this?
To create an inset axes you may use mpl_toolkits.axes_grid1.inset_locator.inset_axes.
Position of inset axes in axes coordinates
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, ax= plt.subplots()
inset_axes = inset_axes(ax,
width=1, # inch
height=1, # inch
bbox_transform=ax.transAxes, # relative axes coordinates
bbox_to_anchor=(0.5,0.5), # relative axes coordinates
loc=3) # loc=lower left corner
ax.axis([0,500,-.1,.1])
plt.show()
Position of inset axes in data coordinates
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, ax= plt.subplots()
inset_axes = inset_axes(ax,
width=1, # inch
height=1, # inch
bbox_transform=ax.transData, # data coordinates
bbox_to_anchor=(250,0.0), # data coordinates
loc=3) # loc=lower left corner
ax.axis([0,500,-.1,.1])
plt.show()
Both of the above produce the same plot
(For a possible drawback of this solution see specific location for inset axes)

How to plot the whole point circle above axis line in matplotlib

Normally when you plot a list of points and axis. Only a part of point will be shown for those intersecting with the axis line, see the first point in this png for an example. How to make sure the whole point circle in shown above the axis line?
You can turn off the clipping by using the parameter clip_on of the plotting functions:
plt.plot(range(10), marker='o', ms=20, clip_on=False)
You can turn off clipping for the resulting plot artist(s) by setting clip_on=False in your call to plot or scatter. Note that you can also modify the clipping box by hand if you have a reference to the artist.
import matplotlib.pyplot as plt
plt.plot([0,1,2], [0,1,2], 'bo', clip_on=False)
produces: