I want to change the scale of x axis in matplotlib in python. I am using following code.
df.iloc[:,5:9].plot(kind="density",subplots=True,layout=(2,2),sharex=False)
I want to have different X axis scale for all X axis. What I tried is following
fig=plt.figure(figsize=(15,15))
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax2=fig.add_subplot(2,2,3)
ax2=fig.add_subplot(2,2,4)
ax1.set_xticks(np.arrange(1,5000,500))
ax2.set_xticks(np.arrange(1,5000,500))
ax3.set_xticks(np.arrange(1,5000,500))
ax4.set_xticks(np.arrange(1,5000,500))
But, when I run this I get empty figure.
You need to operate on the axes in which the plots live, not in some newly created empty axes.
axes = df.plot(kind="density",subplots=True,layout=(2,2),sharex=False)
axes[0,0].set_xticks(...)
Related
the image of what I mean in my question
I'm using BMP280 to measure Temperature and Pressure using Raspberry.
I'm using matplotlib to make a graph, but the matplotlib simplify my Y axis bi adding +9.967e2.
is there any way to avoid matplotlib simplify my Y axis. Sorry I'm new to this so I don't know much.
I tried to search in google but I don't find anything. Maybe I'm using the wrong keyword as I don't know what should I search.
You can turn off the offset as shown in the examples here. For example, if you've made you plot with:
from matplotlib import pyplot as plt
plt.plot(x, y)
then you can turn off the offset with
ax = plt.gca() # get the axes object
# turn off the offset (on the y-axis only)
ax.ticklabel_format(axis="y", useOffset=False)
plt.show()
See the ticklabel_format docs for more info.
I am trying to build a graph using matplotlib, and I am having trouble placing descriptive text on the graph itself.
My y values range from .9 to 1.65, and x ranges from the dates 2001 to 2021 and are sourced from a datetime series.
Here are the basics of what I am working with:
fig, ax = plt.subplots(figsize=(10,7))
I know that I have to use ax.text() to place any text, but whenever I try to enter basically any values for the x and y coordinates of the text, the entire graph disappears when I re-run the cell. I have plotted the following line, but if I use the same coordinates in ax.text(), I get the output I just described. Why might this be happening?
plt.axhline(y=1.19, xmin=.032, xmax=.96)
By default, the y argument in the axhline method is in data coordinates, while the xmin and xmax arguments are in axis coordinates, with 0 corresponding to the far left of the plot, and 1 corresponding to the far right of the plot. See the axhline documentation for more information.
On the other hand, both the x and y arguments used in the text method are in data coordinates, so you position text relative to the data. However, you can change this to axis coordinates using the transform parameter. By setting this to ax.transAxes, you actually indicate that the x and y arguments should be interpreted as axis coordinates, again with 0 being the far left (or bottom) of the plot, and 1 being the far right (or top) of the plot. In this case, you would use ax.text as follows:
ax.text(x, y, 'text', transform=ax.transAxes)
Again, see the text documentation for more information.
However, it sounds like you might want to combine data and axis coordinates to place your text, because you want to reuse the arguments from axhline for your text. In this case, you need to create a transform object that interprets the x coordinate as axis coordinate, and the y coordinate as data coordinate. This is also possible by creating a blended transformation. For example:
import matplotlib.transforms as transforms
# create your ax object here
trans = transforms.blended_transform_factory(x_transform=ax.transAxes, y_transform=ax.transData)
ax.text(x, y, 'text', transform=trans)
See the Blended transformations section of the transformations tutorial for more information.
In short, you can refer to the following figure to compare the results of these various transformations:
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
fig, ax = plt.subplots()
ax.set_xlim(0, 2)
ax.set_ylim(0, 2)
# note that the line is plotted at y=1.5, but between x=1.6 and x=1.8
# because xmin/xmax are in axis coordinates
ax.axhline(1.5, xmin=.8, xmax=.9)
# x and y are in data coordinates
ax.text(0.5, 0.5, 'A')
# here, x and y are in axis coordinates
ax.text(0.5, 0.5, 'B', transform=ax.transAxes)
trans = transforms.blended_transform_factory(x_transform=ax.transAxes, y_transform=ax.transData)
# here, x is in axis coordinates, but y is in data coordinates
ax.text(0.5, 0.5, 'C', transform=trans)
I am struggling to 'translate' the instructions I find for Python to the use of Pyplot in Julia. This must be a simple question, but do you know how to set the number of ticks in a plot in Julia using Pyplot?
If you have
x = [1,2,3,4,5]
y = [1,3,6,8,11]
you can
PyPlot.plot(x,y)
which draws the plot
and then do
PyPlot.xticks([1,3,5])
for tics at 1,3 and 5 on the x-axis
PyPlot.yticks([1,6,11])
for tics at 1,6 and 11 on the y-axis
Tic spacing
if you want fx 4 tics and want it evenly spaced and dont mind Floats, you can do
collect(linspace(x[1], x[end], 4).
If you need the tics to be integers and you want 4 tics, you can do
collect(x[1]:div(x[end],4):x[end])
Edit
Maybe this wont belong here but atleast you'll see it...
whenever you're looking for a method that's supposed to be in a module X you can find these methods by typing in the REPL X. + TAB key
to clarify, if you want to search a module for a method you suspect starts with an x, like xticts, in the REPL (terminal/shell) do
PyPlot.x
and press TAB twice and you'll see
julia> PyPlot.x
xkcd xlabel xlim xscale xticks
and if you're not sure exactly how the method works, fx its arguments, and there isnt any help available, you can call
methods(PyPlot.xticks)
to see every "version" that method has
Bonus
The module for all the standard methods, like maximum, vcat etc is Base
After some trying and searching, I found a way to do it. One can just set the number of bins that should be on each axis. Here is a minimal example:
using PyPlot
x = linspace(0, 10, 200)
y = sin(x)
fig, ax = subplots()
ax[:plot](x, y, "r-", linewidth=2, label="sine function", alpha=0.6)
ax[:legend](loc="upper center")
ax[:locator_params](axis ="y", nbins=4)
The last line specifies the number of bins that should be used on the y-axis. Leaving the argument axis unspecified will set that option for both axis at the same value.
I am trying to create a plot with a colorbar, with custom tick labels. When I try to create a label for a colorbar, it reverts to the original tick labels.
z = np.add(relzvals, shift_val)
fig=plt.figure()
plt.contourf(x,y,z,25)
ax = plt.colorbar()
ax.set_label('cbar_label',rotation=270)
ax.set_ticklabels(labels,update_ticks=True)
How can I get both customizations?
UPDATE: For context, the main program require translated values, i.e. relzvals = z + shift_val, and the matrix has to be translated back to z for plotting.
I checked the values of z before coming inside plt.contourf() but it contains the original values.
I have Python 2.7.11 and Matplotlib 1.3.1.
I'm having trouble giving colorbars to a grid of line plots in Matplotlib.
I have a grid of plots, which each shows 64 lines. The lines depict the penalty value vs time when optimizing the same system under 64 different values of a certain hyperparameter h.
Since there are so many lines, instead of using a standard legend, I'd like to use a colorbar, and color the lines by the value of h. In other words, I'd like something that looks like this:
The above was done by adding a new axis to hold the colorbar, by calling figure.add_axes([0.95, 0.2, 0.02, 0.6]), passing in the axis position explicitly as parameters to that method. The colorbar was then created as in the example code here, by instantiating a ColorbarBase(). That's fine for single plots, but I'd like to make a grid of plots like the one above.
To do this, I tried doubling the number of subplots, and using every other subplot axis for the colorbar. Unfortunately, this led to the colorbars having the same size/shape as the plots:
Is there a way to shrink just the colorbar subplots in a grid of subplots like the 1x2 grid above?
Ideally, it'd be great if the colorbar just shared the same axis as the line plot it describes. I saw that the colorbar.colorbar() function has an ax parameter:
ax
parent axes object from which space for a new colorbar axes will be stolen.
That sounds great, except that colorbar.colorbar() requires you to pass in a imshow image, or a ContourSet, but my plot is neither an image nor a contour plot. Can I achieve the same (axis-sharing) effect using ColorbarBase?
It turns out you can have different-shaped subplots, so long as all the plots in a given row have the same height, and all the plots in a given column have the same width.
You can do this using gridspec.GridSpec, as described in this answer.
So I set the columns with line plots to be 20x wider than the columns with color bars. The code looks like:
grid_spec = gridspec.GridSpec(num_rows,
num_columns * 2,
width_ratios=[20, 1] * num_columns)
colormap_type = cm.cool
for (x_vec_list,
y_vec_list,
color_hyperparam_vec,
plot_index) in izip(x_vec_lists,
y_vec_lists,
color_hyperparam_vecs,
range(len(x_vecs))):
line_axis = plt.subplot(grid_spec[grid_index * 2])
colorbar_axis = plt.subplot(grid_spec[grid_index * 2 + 1])
colormap_normalizer = mpl.colors.Normalize(vmin=color_hyperparam_vec.min(),
vmax=color_hyperparam_vec.max())
scalar_to_color_map = mpl.cm.ScalarMappable(norm=colormap_normalizer,
cmap=colormap_type)
colorbar.ColorbarBase(colorbar_axis,
cmap=colormap_type,
norm=colormap_normalizer)
for (line_index,
x_vec,
y_vec) in zip(range(len(x_vec_list)),
x_vec_list,
y_vec_list):
hyperparam = color_hyperparam_vec[line_index]
line_color = scalar_to_color_map.to_rgba(hyperparam)
line_axis.plot(x_vec, y_vec, color=line_color, alpha=0.5)
For num_rows=1 and num_columns=1, this looks like: