This question already has answers here:
In matplotlib, how do you draw R-style axis ticks that point outward from the axes?
(2 answers)
How to set default tick params in python/matplotlib?
(1 answer)
Closed 2 years ago.
Simple problem: With matplotlib, I want to have this style preset:
Bottom and left ticks: direction out, label on
top and right ticks: direction in, label off
I want to have this style as a preset, so I dont have to do it for every single plot. The following code gives me the top and right ticks, but I cant manage to change their direction.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["xtick.top"] = True
plt.rcParams["ytick.right"] = True
somearray=np.arange(0.0, 1.0, 0.1)
plt.figure()
plt.plot(somearray[:], somearray[:])
plt.xlabel('x')
plt.ylabel('y')
plt.show()
You can use x(y)ticks.direction to set the ticks inside. It's simple to update the parameters in the form of a dictionary.
import numpy as np
import matplotlib.pyplot as plt
# plt.rcParams["xtick.top"] = True
# plt.rcParams["ytick.right"] = True
# plt.rcParams['xtick.direction'] = 'in'
# plt.rcParams['ytick.direction'] = 'in'
params = {"xtick.top": True, "ytick.right": True, "xtick.direction": "in", "ytick.direction": "in"}
plt.rcParams.update(params)
somearray = np.arange(0.0, 1.0, 0.1)
plt.figure()
plt.plot(somearray[:], somearray[:])
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Related
This question already has answers here:
fill_between with matplotlib and a where condition of two lists
(1 answer)
Matplotlib fill_between edge effect with `where` argument
(1 answer)
Fill between x and baseline x position in Matplotlib
(1 answer)
How to avoid gaps with matplotlib.fill_between and where
(1 answer)
Closed 1 year ago.
I'm plotting a blackbody curve and would like to fill in the area under the curve in the range of between 3 and 5 micron. However, I'm not sure how to use the fill_between or fill_betweenx plt commands here
import numpy as np
import matplotlib.pyplot as plt
from astropy import units as u
from astropy.modeling import models
from astropy.modeling.models import BlackBody
from astropy.visualization import quantity_support
bb = BlackBody(temperature=308.15*u.K)
wav = np.arange(1.0, 50.0) * u.micron
flux = bb(wav)
with quantity_support():
plt.figure()
plt.plot(wav, flux, lw=4.0)
plt.fill_between(wav,flux, min(flux), color = 'red')
plt.show()
This plots a fill under the whole curve, but only the 3-5micron part is desired to be filled.
example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 100) # Sample data.
# Note that even in the OO-style, we use `.pyplot.figure` to create the figure.
fig, ax = plt.subplots() # Create a figure and an axes.
print(x)
ax.plot(x, x, label='linear') # Plot some data on the axes.
ax.set_xlabel('x label') # Add an x-label to the axes.
ax.set_ylabel('y label') # Add a y-label to the axes.
ax.set_title("Simple Plot") # Add a title to the axes.
ax.legend() # Add a legend.
plt.fill_between(x[:5],x[:5])
plt.show()
You can change the value 5 and play with it, you'll understand quickly. first parameter is Y positions , second is X positions.
fill_betweenx is just the same, but it will fill the other way around.
edit: As said in comments, it is better to use plt.fill_between(x,x, where = (x>0)&(x<0.2)). Both works, second solution is more explicit.
This question already has answers here:
matplotlib y-axis label on right side
(4 answers)
Closed 2 years ago.
I have this chart below:
I would want the y-axis for the lower subplot to be plotted to the opposite side since that would make more sense. Is there a method for this? The ax.invert_yaxis() simply inverts the labels.
Note: For the curious, I simply used .invert_xaxis() to plot inverted bars.
I guess, what you are looking for is
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
of an axis object.
So with #meTchaikovsky's MVE code, you'll get
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(1,10,10)
y0 = np.random.randint(0,30,size=10)
fig,ax = plt.subplots(nrows=2,ncols=1,figsize=(8,6))
ax[1].set_xlim(0,30)
ax[0].barh(x,y0,color='violet')
ax[0].set_ylabel("Y-Axis")
ax[1].set_xlim(30,0)
ax[1].barh(x,y0,color='deepskyblue')
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
ax[1].set_ylabel("Y-Axis")
plt.show()
This question already has an answer here:
Moving matplotlib xticklabels by pixel value
(1 answer)
Closed 5 years ago.
I'm doing a bar plot with long labels, which I've rotated 45 degrees and set to be right-aligned. However, the tick labels are still a bit away from the ticks, making the plot look strange. How do move all the labels a few points to the right?
Here is my current code:
import seaborn as sns
import pylab as plt
plt.figure()
ax = sns.barplot(x="item", y="dist", hue="dset", data=df)
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
EDIT: Please take look at the right-aligned subplot in stackoverflow.com/a/14854007/1452257 for an example. I can also copy the code/image to this post if you prefer.
From ImportanceOfBeingErnest's answer here, I got the following on translating tick labels in a general, arbitrary way:
import matplotlib.transforms as mtrans
# ...
trans = mtrans.Affine2D().translate(20, 0)
for t in ax.get_xticklabels():
t.set_transform(t.get_transform()+trans)
This question already has answers here:
Overlapping axis tick labels in logarithmic plots
(2 answers)
Matplotlib: setting x-limits also forces tick labels?
(1 answer)
Closed 5 years ago.
I'm plotting with matplotlib. When I set the x-scale to 'log' and change the tick labels and formatting to display linearly, the logspace tick labels don't go away, and I end up with two sets of xticklabels (one linear and one logspace).
This didn't happen on another machine, so I think it is version-specific? Right now I'm working in Jupyter Notebook with matplotlib 2.0.2 and python 3.6.1.
MWE:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
%matplotlib inline
fig, ax = plt.subplots(1, 1)
xmin = 5
xmax = 50
ax.set_xscale('log')
ax.set_xticklabels(np.logspace(np.log10(xmin), np.log10(xmax), num=6))
ax.set_xticks(np.logspace(np.log10(xmin), np.log10(xmax), num=6))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
ax.set_xlim([xmin, xmax])
This question already has answers here:
Embedding small plots inside subplots in matplotlib
(4 answers)
Closed 3 years ago.
I'd like to make a graph like that:
the problem is, I've got the data from some external files, and I can make the background graph, but I have no idea how to add another graph inside of the one that I already have and change the data to have different results in both of them:
Below I am adding the code I am using to do the background graph.
Hope someone can help.
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
plt.rc('text',usetex=True)
font = {'family':'serif','size':16}
plt.rc('font',**font)
plt.rc('legend',**{'fontsize':14})
matplotlib.rcParams['text.latex.preamble']=[r'\usepackage{amsmath}']
data=np.loadtxt(r'C:\...\file.txt')
plt.plot(data[:,0],data[:,6],linewidth = 3,label='B$_0$ = 1.5 T d',linestyle= '--', color='black')
plt.show()
There's more than one way do to this, depending on the relationship that you want the inset to have.
If you just want to inset a graph that has no set relationship with the bigger graph, just do something like:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
# These are in unitless percentages of the figure size. (0,0 is bottom left)
left, bottom, width, height = [0.25, 0.6, 0.2, 0.2]
ax2 = fig.add_axes([left, bottom, width, height])
ax1.plot(range(10), color='red')
ax2.plot(range(6)[::-1], color='green')
plt.show()
If you want to have some sort of relationship between the two, have a look at some of the examples here: http://matplotlib.org/1.3.1/mpl_toolkits/axes_grid/users/overview.html#insetlocator
This is useful if you want the inset to be a "zoomed in" version, (say, at exactly twice the scale of the original) that will automatically update as you pan/zoom interactively.
For simple insets, though, just create a new axes as I showed in the example above.
You can do this with inset_axes method (see docs):
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
inset_ax = inset_axes(parent_axes,
width="30%", # width = 30% of parent_bbox
height=1., # height : 1 inch
loc=3)
See this example for a full demo.