How to replace ticks in Matplotlib? - python

I would like to change the ticks intervals on a figure, which looks like that:
I use this:
plt.xticks(np.arange(1945, 2016, 10))
However, what I finally get is:
As you can see, I can't take out the smaller ticks. I tried this line:
ax.tick_params(axis='x', length=0)
But without success, since it show this:
I lost the ticks I would like to plot.
To plot, my code is:
for row, plot in enumerate(toplot):
for col, country in enumerate(countries):
ax = axes[row][col]
(dx[(plot, country)]
.plot(ax=ax, c=color)
)
Any idea?

It looks like what you want to do is disable the "minor ticks". Here you can find the official documentation about it, and another thread on stackoverflow about it. I did not try it myself bu just adding ax.minorticks_off() should do the trick !

Related

Matplotlib: how to create vertical lines between x-values on barplot?

I am currently working on a barplot which looks like this:
In order to provide more clarity, I would like to add a vertical line that should point out the separation between the x values. I've drawn an example here:
In order to draw the diagram, I am using the plot function from pandas on the corresponding dataframe:
produced_items.plot(kind='bar', legend=True,title="Produced Items - Optimal solution",xlabel="Months",ylabel='Amount',rot=1,figsize=(15,5),width=0.8)
I hoped to find a parameter in matplotlib, that yields the desired behavior, but I didn't find anything, that could help.
Another solution that comes in my mind is to plot a vertical line between each x-value but i wonder if there is a built-in way to accomplish this?
Thanks in advance.
Let's try modifying the minor ticks:
from matplotlib.ticker import MultipleLocator
ax = df.plot.bar()
# set the minor ticks
ax.xaxis.set_minor_locator(MultipleLocator(0.5))
# play with the parameters to get your desired output
ax.tick_params(which='minor', length=15, direction='in')
Output:

Removing label in Boxplot in Python

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 to get color of most recent plotted line in pandas df.plot()

I would like to get the color of the my last plot
ax = df.plot()
df2.plot(ax=ax)
# how to get the color of this last plot,
#the plot is a single timeseries, there is therefore a single color.
I know how to do it in matplotlib.pyplot, for those interested see for instance here but I can't find a way to do it in pandas. Is there something acting like get_color() in pandas?
You cannot do the same with DataFrame.plot because it doesn't return a list of Line2D objects as pyplot.plot does. But ax.get_lines() will return a list of the lines plotted in the axes so you can look at the color of the last plotted line:
ax.get_lines()[-1].get_color()
Notice (don't know if it was implicit in the answer by Goyo) that calls to pandas objects' .plot() precisely return the ax you're looking for, as in:
plt1 = pd.Series(range(2)).plot()
color = plt1.lines[-1].get_color()
pd.Series(range(2, 4)).plot(color=color)
This is not much nicer, but might allow you to avoid importing matplotlib explicitly

Remove axes in matplotlib subplots?

I've got a pandas dataframe with 4 columns and a date range as the index. After showing the trend lines on four subplots using this code, I realized I don't want the y axis ticks or labels, but I can't find any advice on removing them from the subplots; everything I try only works on the bottom plot.
plot4 = CZBCdf2.plot(subplots=True,figsize=(10,4),sharex=True)
The typical way of removing axis in matplotlib is:
import matplotlib.pyplot as plt
plt.axis('off')
This, however, is a general instruction in matplotlib. To set the axis to invisible you can do (using a subplot):
ax.xaxis.set_visible(False) # same for y axis.
You seem to be calling the plot from other source. If this instructions don't do the stuff you need provide more of your code to see what might be the procedure to achieve that.
A complete solution to remove anything around the plot
figure, axis = plt.subplots(1, figsize=[10,3])
axis.plot(...)
axis.xaxis.set_visible(False)
axis.yaxis.set_visible(False)
for spine in ['top', 'right', 'left', 'bottom']:
axis.spines[spine].set_visible(False)
figure.savefig('demo.png', bbox_inches='tight', transparent="True", pad_inches=0, )
Set yticks=[]
So, in your example:
plot4 = CZBCdf2.plot(subplots=True,figsize=(10,4),sharex=True, yticks=[])

Reduce space between first histogram bar and y-axis

I have a histogram shown here which I made using the following:
import pylab as pl
fd = FreqDist(list(industries))
X = np.arange(len(fd))
pl.bar(X, fd.values(), align='center', width=0.15)
pl.xticks(X, fd.keys(), rotation=90)
pl.tick_params(labelsize=8)
ymax = max(fd.values()) + 1
pl.ylim(0, ymax)
pl.subplots_adjust(bottom=0.3)
pl.savefig('internalDoorCount.jpg')
However I need the gap to reduce between the y-axis and the first histogram bar. Also how do you prevent overlapping of text?
You can try to avoid overlapping of the text by using this function:
pl.gcf().autofmt_xdate(bottom=0.3, rotation=-30, ha="left")
It's created for rotating date tick labels, but it should work good here. But you most probably have to either reduce the font size, and/or increase the width of your figure.
Assuming pl is matplotlib.pyplot, use pl.xlim. Because I'm not sure what values your x-axis takes, try
pl.xlim(min(X), max(X))
I cannot upvote and I'm amazed how old answers here are still helpful. So, as I still don't have points to comment, I'm answering here to correct a typo from #wflynny and say his answer is simple and works. The actual beginning of the code is "plt", instead of "pl":
plt.xlim(min(x),max(x))
The complete documentation is here.

Categories

Resources