I have been trying to plot a scatterplot matrix using the great example given by Joe Kington:
However, I would like to add xlabels and ylabels on the subplots where I have displayed ticks. When you change the positions of the ticks, the associated x/ylabel does not follow.
I have not been able to find an option to change the location of the label; I was hoping to find something like ax.set_xlabel('XLabel',position='top') but it does not exist.
This is what I get finally,
For example I would like X axis4 to be above the ticks.
If you want to change the x-label from bottom to top, or the y-label from left to right, you can (provided the specific suplot is called ax) do it by calling:
ax.xaxis.set_label_position('top')
ax.yaxis.set_label_position('right')
If you for example want the label "X label 2" to stay where it is but don't overlap the other subplot, you can try to add a
fig.tight_layout()
just before the fig.show().
Related
I am using Plotly and Python to chart a bar plot. On the x-axis, Plotly arranges the values from each trace around the centre of the tick mark.
This is what I am getting now:
I would like to have the data points (and labels) in between the tick marks. In the example chart, this would mean all the bars centered around 0-2kw would move left of the first tick and the label centered, all the bars around 2-4kw would move between the first and second ticks and the label centered, etc..
I am using tickmode=array, ticktext as an array and also set tickson=boundaries, but it's still the same.
Is there a way to do this?
(Not sure if this makes any difference but there are multiple charts in subplots)
Answering my own question.
Normally setting tickon=boundaries should do the trick, but it doesn't seem to work in conjunction with tickmode=array and ticktext.
The solution for me was to create the labels array and provide it to the bar chart as the x parameter, something similar to this:
fig = go.Figure(data=go.Bar(name='Trace1', x=['0-2kw', '2-4kw', '4-6kw', '6-8kw'], y=[0.2, 0.2, 0.2, 0.4]))
fig.update_xaxes(showgrid=True, tickson='boundaries')
Doing this in my code now the data bars are in between the grid lines:
I'm making a map using matplotlib.pyplot and I used the gridlines feature to create "labels" on the x and y axis of degrees latitude and longitude. I set the gridlines color to "none" to avoid having the gridlines there. However, these labels appear on each side of the plot and, at one point, coincide with my colorbar. Is there a way I could make these gridline labels only appear on the bottom and left of the plot? I can't find a list of the available kwargs anywhere. This is the code I used:
ax.gridlines(draw_labels=True, color="none")
And here is an image of the map. I would ideally like to remove the degree labels on the right and top axes.
You can achieve what you need with these relevant code:-
# minor change to the existing line of code
gls = ax.gridlines(draw_labels=True, color="none")
# other lines of code
# add these before plotting
gls.top_labels=False # suppress top labels
gls.right_labels=False # suppress right labels
I have created the following code, which prints a plot and formats the axis labels and ticks in a way that is useful to me. I have a problem with tight_layout, which leaves my vertically rotated x-axis tick labels as well as the x-axis label outside the figure window.
To try and solve the problem, what I did was to manually rescale the plot window, and set the rect tuple manually from the figure window. After some tries, I found that the optimal values for (left, bottom, right, top) in my case were [0.163, 0.391, 0.905, 0.977]. Next, I thought I should incorporate that to my code, so that my plots emerge with correct sizing in the first place: To that end, I used the command:
fig.tight_layout(rect=[0.163, 0.391, 0.905, 0.977])
However, it did not work, and the figure emerges with different rect values than the ones I set.
Question 1: How can I set the rect values from my code, rather than setting them manually?
Question 2: Is there a better/easier alternative to achieve the desired functionality?
# dt_objects is a list of datetime objects. My x-axis is timestamps
# for y_axis, set any series. The code will set the y axis based on the min,max value of y-values
matdates=date2num(dt_objects)
x_axis=matdates
fig,ax = plt.subplots()
ax.plot_date(x_axis,y_axis,markersize=8)
ax.axhline(y=y_axis.mean(),linestyle='--',color='red',alpha=0.5)
ax.xaxis.set_major_locator(AutoDateLocator(minticks=1, maxticks=5)) #Set position of Major X ticks
ax.xaxis.set_minor_locator(AutoDateLocator(minticks=10, maxticks=30)) #Set position of Minor X ticks
ax.xaxis.set_major_formatter( DateFormatter('%Y/%m/%d-%H:%M:%S')) #Set format of Major X ticks
ax.xaxis.set_minor_formatter( DateFormatter('%H:%M:%S')) #Set format of X ticks
ax.tick_params(axis='x',which='major',rotation=90,labelsize=14) #Set parameters of Major X ticks
ax.tick_params(axis='x',which='minor',rotation=80,labelsize=12) #Set parameters of Major X ticks
plt.setp(ax.get_xticklabels(), fontsize=14, fontweight="bold") #Set font of Major X ticks
ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) #Set format of Major Y ticks
ax.tick_params(axis='y',which='major',labelsize=14)
calculateYpadding=(y_axis.max()-y_axis.min())*0.1 # Padding is 10% of the max difference in y values :)
ax.set_ylim(round(y_axis.min(),2)-calculateYpadding, round(y_axis.max(),2)+calculateYpadding) #Set boundaries of Y axis
ax.yaxis.set_major_locator(MaxNLocator(nbins = 'auto',min_n_ticks = 5))
plt.grid()
ax.set_xlabel("Time",style='italic',fontsize=14)
ax.xaxis.set_label_coords(1.08, -0.1)
ax.set_ylabel(str(MeasurementType),labelpad=10,style='italic', fontsize=14)
#ax.yaxis.set_label_coords(-0.1, 0.5)
#plt.xlabel("Time",horizontalalignment='right', position=(1,60))\
#ax.set_title(str(MeasurementType),fontweight="bold", pad=20,fontsize=20)
rstButton.config(state=tk.NORMAL)
fig.tight_layout(rect=[0.163, 0.391, 0.905, 0.977])
plt.show()
EDIT: Since I was told my question is not clear, I am including two screenshots to better explain the problem. Here is the result of the above-mentioned code. Also, on the bottom left, you can see on the window that top, bottom, left, right have different values than the ones set at rect tuple in my code.
My desired output is this:
It is achieved by manually tweaking the parameters of the figure, until it reaches a point that is satisfactory. It is from here that i extracted the values and placed them in the rect tuple, but it did not work. Hopefully it is clearer now what I want to achieve, and what the problem is.
EDIT 2: Here are the results of the suggested solution
fig,ax = plt.subplots(constrained_layout=True)
As you can see, the labels of both axles are not correctly placed.
Try:
fig, ax = plt.subplots(constrained_layout=True)
I'm unable to remove the label "Age" under each box plot shown below. Its autogenerated and can't get rid of it. Here is my code and output:
dataset.boxplot(column=['Age'], by=None, ax=None, fontsize=None, rot=0,
grid=True, figsize=None, layout=None, return_type=None)
plt.suptitle('Attrition by Age')
plt.xlabel('test')
plt.title('test6')
plt.subplot(121)
plt.xlabel('test2')
plt.title('test3')
plt.ylabel('test5')
enter image description here
This is because here "Age" is not an axis label, instead it is a tick. So you can add something like this:
plt.xticks([1], [''])
to remove the first tick.
And there are many other ways to remove or change ticks. For example, this post describes how to remove ticks on different axes.
How can I prevent the labels of xticks from overlapping with the labels of yticks when using hist (or other plotting commands) in matplotlib?
There are several ways.
One is to use the tight_layout method of the figure you are drawing, which will automatically try to optimize the appareance of the labels.
fig, ax = subplots(1)
ax.plot(arange(10),rand(10))
fig.tight_layout()
An other way is to modify the rcParams values for the ticks formatting:
rcParams['xtick.major.pad'] = 6
This will draw the ticks a little farter from the axes. after modifying the rcparams (this of any other, you can find the complete list on your matplotlibrc configuration file), remember to set it back to deafult with the rcdefaults function.
A third way is to tamper with the axes locator_params telling it to not draw the label in the corner:
fig, ax = subplots(1)
ax.plot(arange(10),rand(10))
ax.locator_params(prune='lower',axis='both')
the axis keywords tell the locator on which axis it should work and the prune keyword tell it to remove the lowest value of the tick
Try increasing the padding between the ticks on the labels
import matplotlib
matplotlib.rcParams['xtick.major.pad'] = 8 # defaults are 4
matplotlib.rcParams['ytick.major.pad'] = 8
same goes for [x|y]tick.minor.pad.
Also, try setting: [x|y]tick.direction to 'out'. That gives you a little more room and helps makes the ticks a little more visible -- especially on histograms with dark bars.