This question already has an answer here:
Changing the length of axis lines in matplotlib
(1 answer)
Closed 1 year ago.
I am interested in creating a plot where only part of the spine is visible (say only for positive values), while the plot is shown for both negative and positive values.
set_position # seems to only set the point where it intersects with the other axis
set_visible # is an on-off switch. It does not allow for partial visibility.
Is there a way to do this?
With ax as the axes, if the x-axis is to show only between 0 and 0.5, then:
ax.spines['bottom'].set_bounds((0, 0.5))
You might need to set the ticks, as well, so, for instance:
ax.set_xticks([0, 0.25, 0.5])
Related
This question already has answers here:
How do I equalize the scales of the x-axis and y-axis?
(5 answers)
Closed 8 months ago.
This post was edited and submitted for review 8 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I'd like to make comparing this Prediction and Test values easier, so I'm thinking two ways to achieve that:
Scale the X and Y axis to the same scale
Plot a linear line (y=x)
Really like to have some way to either 'exclude' the outliers or perhaps 'zoom in' to the area where the points are dense, without manually excluding the outliers from the dataset (so its done automatically). Is this possible?
sns.scatterplot(y_pred, y_true)
plt.grid()
Looked around and tested plt.axis('equal') as mentioned on another question but it didn't seem quite right. Tried using plt.plot((0,0), (30,30)) to create the linear plot but it didn't show anything. Any other input on how to visualise this would be really appreciated as well. Thanks!
There are short ways to achieve everything you've suggested:
Force scaled axes with matplotlib.axes.Axes.set_aspect.
Add an infinite line with slope 1 through he origin with matplotlib.axes.Axes.axline
Set your plot to interactive mode, so you can pan and zoom. The way to do this depends on your environment and is explained in the docs.
Best to combine them all.
import matplotlib.pyplot as plt
from numpy import random
plt.ion() # activates interactive mode in most environments
plt.scatter(random.random_sample(10), random.random_sample(10))
ax = plt.gca()
ax.axline((0, 0), slope=1)
ax.set_aspect('equal', adjustable='datalim') # force equal aspect
To plot the linear line:
plt.plot([0,30], [0,30])
To scale x and y axis to same scale (see doc for set_aspect):
plt.xlim(0, 30)
plt.ylim(0, 30)
plt.gca().set_aspect('equal', adjustable='box')
plt.draw()
From the doc for set_aspect:
Axes.set_aspect(aspect, adjustable=None, anchor=None, share=False)
Set the aspect ratio of the axes scaling, i.e. y/x-scale
aspect='equal': same as aspect=1, i.e. same scaling for x and y.
This question already has answers here:
Why is matplotlib's notched boxplot folding back on itself?
(1 answer)
strange shape of the boxplot using matplotlib
(1 answer)
Unintended Notched Boxplot from Matplotlib, Error from Seaborn
(2 answers)
Closed last year.
I am trying to create a box plot with matplotlib library of python. The code is given below.
fig, ax = plt.subplots(figsize=(8, 6))
bp = ax.boxplot([corr_df['bi'], corr_df['ndsi'], corr_df['dbsi'], corr_df['mbi']], patch_artist = True, notch ='True', vert = 1)
ax.set_title("Spearman’s correlation coefficient for Soil indices", fontsize=14)
ax.set_xlabel("Indices", fontsize=14)
ax.set_ylabel("Spearman’s correlation coefficient", fontsize=14)
colors = ['#088A08', '#FFFF00','#01DFD7', '#FF00FF', '#3A01DF']
for patch, color in zip(bp['boxes'], colors):
patch.set_facecolor(color)
ax.grid()
ax.set_xticklabels(['bi', 'ndsi', 'dbsi', 'mbi'])
This creates an image like this :
I am not able to understand the 1st and 3rd boxplot. These two (box plots of bi and dbsi) have neck-like structures in them, which the other two boxplots don't have. What does this show? The interpretation of the boxplot as described on the web doesn't include this part.
In your example, the argument notch is set to True so according to the doc, it displays:
notch bool, default: False
Whether to draw a notched boxplot (True), or a rectangular boxplot (False). The notches represent the confidence interval (CI) around the median. The documentation for bootstrap describes how the locations of the notches are computed by default, but their locations may also be overridden by setting the conf_intervals parameter.
Specifically the behavior (flipped appearance) you're describing is documented as follow:
Note
In cases where the values of the CI are less than the lower quartile
or greater than the upper quartile, the notches will extend beyond the
box, giving it a distinctive "flipped" appearance. This is expected
behavior and consistent with other statistical visualization packages.
You will find more details in this answer.
This question already has answers here:
Improve subplot size/spacing with many subplots
(8 answers)
Closed 1 year ago.
Hi I'm very new to Python, and I'm trying to fix the labels because they overlap, (as seen in the picture). I figured the hspace and the wspace is the columns, but I'm not sure exactly how to adjust everything else in the labels, I don't want to mess with the x axis. Is there a way to make this plot look clearer?
Here's what I have:
_, axes = plt.subplots(nrows=6, ncols=6, sharex=True)
plt.suptitle('mean activity duration by time of day')
plt.subplots_adjust(hspace=0.5, wspace=0.5)
for ax, (activity, df) in zip(axes.ravel(), df_all.groupby('e')):
(df.groupby('f')
.d
.mean()
.plot(ax=ax,
kind='bar',
title=activity,
xlabel='time'))
6 x 6 bar graph:
Use constrained_layout.
use a larger figure size so your titles are not larger than your axes
use a smaller font size for the titles.
You can use tight_layout if you prefer, but constrained_layout is more flexible.
You can try to use plt.tight_layout, adjusts subplot params so that the subplot(s) fits in to the figure area
This question already has answers here:
secondary_y=True changes x axis in pandas
(2 answers)
Plot multiple Y axes
(3 answers)
Closed 4 years ago.
I want to add secondary y-axis. I have my data in CSV with three column date, lscc and cc. I want to add LSCC as first y-axis and CC as secondry. so far I have done this
df=pd.read_csv("E29Lsccvalue.csv", index_col='Date' )
plt.ylabel("")
plt.xlabel("Low level Similarity Class Cohesion (LSCC) Evolution")
df.plot(kind="line", marker='o',legend=None)
plt.xticks(rotation=90)
plt.show()
thanks
Within matplotlib I have used twinx() when I want to utilize the existing X-axis I have created, yet plot more data on top with a different Y axis. In your case with df as the first plot object:
axCC = df.twinx() # second axis sharing the same X axis of the original
Then you can include plots, labels, and other parameters referenced to this axis through calls such as:
axCC.set_ylabel("ExampleLabel",color="tab:red")
axCC.plot(xData,yData,color="blue")
Etc, etc.
A fully functional example with more detail is shown here
Although no reproducible date is provided, I guess you can achieve the desired result by doing this:
ax = df.plot(secondary_y='CC')
eventually adding all your ax customization required
edit: dotted line customization
Suppose you need a dotted vertical line at a certain position on your x-axis (in this example, at position 2 from your pandas index), use axvline and ':' as linestyle (dots)
ax = a.plot(secondary_y='Price')
ax.axvline(a.index.values[2], linestyle=':')
This question already has answers here:
Creating figure with exact size and no padding (and legend outside the axes)
(2 answers)
How to put the legend outside the plot
(18 answers)
Closed 4 years ago.
I am trying to put a legend below a graph but keeping the figure size fixed.
Is this possible?
I saw How to put the legend out of matplotlib plot and https://stackoverflow.com/a/4701285/7746941 but the first one does not address fitting the legend within a predefined figure size while the second one does not do this generically (there is an example where the axes width is shrunk by 0.8 to accommodate the legend) .
Below is my current solution that anchors the legend at the bottom of the graph but the legend does not fit the figure.
I cannot figure out how to determine the height of the legend box to move the axis up by that amount.
import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})
ax = df.plot(figsize=(4,4))
tight_box = ax.transAxes.inverted().transform(ax.get_tightbbox(ax.figure.canvas.get_renderer()))
leg = ax.legend(bbox_to_anchor=(0,tight_box[0][1],1,0), loc='upper center')