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:
Related
graph
how do I make this graph infill all the square around it? (I colored the part that I want to take off in yellow, for reference)
Normally I use two methods to adjust axis limits depending on a situation.
When a graph is simple, axis.set_ylim(bottom, top) method is a quick way to directly change y-axis (you might know this already).
Another way is to use matplotlib.ticker. It gives you more utilities to adjust axis ticks in your graph.
https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-formatters.html
I'm guessing you're using a list of strings to set yaxis tick labels. You may want to set locations (float numbers) and labels (string) of y-axis ticks separatedly. Then set the limits on locations like the following snippet.
import matplotlib.pyplot as plt
import matplotlib.ticker as mt
fig, ax = plt.subplots(1,1)
ax.plot([0,1,2], [0,1,2])
ax.yaxis.set_major_locator(mt.FixedLocator([0,1,2]))
ax.yaxis.set_major_formatter(mt.FixedFormatter(["String1", "String2", "String3"]))
ax.set_ylim(bottom=0, top=2)
It gives you this: generated figure
Try setting the min and max of your x and y axes.
I am trying to display a chart using matplotlib. But my labels are so big that they are overlapping each other. I want to show it cleanly no overlapping. How can I do that? I am now using below code:
import matplotlib.pyplot as plt
x = ['jdwdw723#gmail.com' ,'emcast.test10#gmail.com', 'pbChinaTester#clp.com']
y = [10,25,6]
plt.plot(x,y)
plt.xlabel("loginId")
plt.ylabel("times appeared in the data")
plt.title("loginId Graph")
plt.tight_layout()
plt.show()
I tried your example code, and it doesn't seem to be overlapping there. There are many possibilities. One, commonly used, is to rotate the labels.
You can do it like this:
plt.xticks(rotation=45)
There are more ideas in Changing the “tick frequency” on x or y axis in matplotlib? and in reducing number of plot ticks.
I created an example notebook here, feel free to duplicate and play with it.
I have a large list of data points of x and y values that I need to put into a histogram with 40 bins but mathlibplot.hist is only letting me enter 1 variable with bins. I've tried hist2d as well but it's not very clean. Any help would be appreciated!
As you have data points x and y, you can simply use hist method to plot histogram.
The following code will help you to create a histogram.
plt.hist([x,y],bins=40, histtype='step',fill=True)
plt.show()
The histogram will look like the following:
If you want to change the style or give it title and labels, you can do it. Here is another histogram with unfilled bars.
If you still face any problem, let me know then.
Maybe you can make use of matplotlib library to solve your purpose:
It will be like imposing 2 histograms on top of each other.
In the below code, I am trying to plot a histograms of y_train and predicted(X_train) in the same space.
You can modify the variables as per your requirement.
import matplotlib.pyplot as plt
plt.hist(y_train, stacked=True,bins=40, label='Actual', alpha=0.5)
plt.hist(regressor.predict(X_train),bins=40, stacked=True, label='Predicted', alpha=0.5)
plt.legend(loc='best')
plt.show()
Hope this helps!
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
I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it?
Do you mean something like this:
>>> from matplotlib import *
>>> plot(xrange(10))
>>> yticks(xrange(10), rotation='vertical')
?
In general, to show any text in matplotlib with a vertical orientation, you can add the keyword rotation='vertical'.
For further options, you can look at help(matplotlib.pyplot.text)
The yticks function plots the ticks on the y axis; I am not sure whether you originally meant this or the ylabel function, but the procedure is alwasy the same, you have to add rotation='vertical'
Maybe you can also find useful the options 'verticalalignment' and 'horizontalalignment', which allows you to define how to align the text with respect to the ticks or the other elements.
In Jupyter Notebook you might use something like this
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plt.xticks(rotation='vertical')
plt.plot(np.random.randn(100).cumsum())
or you can use:
plt.xticks(rotation=90)
Please check out this link:
https://python-graph-gallery.com/7-custom-barplot-layout/
import matplotlib.pyplot as plt
heights = [10, 20, 15]
bars = ['A_long', 'B_long', 'C_long']
y_pos = range(len(bars))
plt.bar(y_pos, heights)
# Rotation of the bars names
plt.xticks(y_pos, bars, rotation=90)
The result will be like this
Hopefully, it helps.
I would suggest looking at the matplotlib gallery. At least two of the examples seem to be relevant:
text_rotation.py for understanding how text layout works
barchart_demo2.py, an example of a bar chart with somewhat more complicated layout than the most basic example.