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.
Related
So I have been trying to generate a heatmap in python such that the Matplotlib graph that is generated does not have any white margins in both x and y axes and the graph's scaling must be 1:1 with respect to the x and y axes units. I have tried many things but the best I have been able to achieve so far is able to remove the x axis white margins but not the y one. Here's an example:
This is what I am getting:
This is what I want:
Here's the code through which I am generating the graph:
plt.style.use('classic')
plt.axis('equal')
plt.pcolormesh(x_mesh,y_mesh,intensity)
plt.plot(x,y,linestyle="None",marker='.',markerfacecolor='white')
#plt.colorbar()
#plt.axis('off')
plt.margins(x=0,y=0)
plt.ylim([0,254])
plt.xlim([0,538])
plt.savefig('plottest.png', dpi=144, bbox_inches='tight', pad_inches=0)
plt.show()
Any help would be highly appreciated! Thanks!
Try changing plt.axis('equal') to plt.axis('scaled'). As the documentation says:
equal: ... Explicit data limits may not be respected in this case.
Hello all i'm currently trying to plot some data using matplotlib. Unfortunately every time I plot the xlabels overlap each other. How can I go about getting this to space out the labels?Code snippet below. my dict has keys of 'neighborhood' and values of int
#do data visualization here
myList = dict.items()
#myList = sorted(myList)
x, y = zip(*myList)
plt.xlabel("Neighborhoods")
plt.ylabel("# of Public Art")
plt.title("Public Art Distribution in Pittsburgh")
plt.xscale('log', base=3)
plt.plot(x, y)
plt.show()
I'm trying to get the labels to not overlap here
EDIT: thank you to the two suggestions of rotation and to increase figure size. By using these two I was able to get it displaying correctly
import matplotlib.ticker as ticker
ax.xaxis.set_major_locator(ticker.MultipleLocator(5))
You can try to set the frequency to five or more.
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 am currently creating a graph that that analyzes the correlation of absorption and concentration (Beer's law). While creating the graph, I've ran into a few problems, and I am now stuck. My plots are not showing up within my graph. Is it due to placement error? If possible, I would like to leave the ticks, labels, and title in the same (or similar format). Sorry in advance for the sloppiness, trying to get the function down before I make it pretty. But anyways, here is the code:
#importing matplotlib to create a graph
import matplotlib.pyplot as plt
#ploting out the points while labeling the graph
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-
03],[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks([1, 2, 3, 4, 5, 6, 7], [str('1.95E-03'), str('9.75E-04'),
str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'),
str('1.95E-06')])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
Your xticks are completely out of the range where your data lives. Remove the line which sets the xticks and your plot is fine
import matplotlib.pyplot as plt
plt.plot([1.95E-06, 9.75E-06, 1.95E-05, 9.75E-05, 1.95E-04, 9.75E-04, 1.95E-03],
[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.show()
If you want to use your custom ticks, you need to set them in the data range, i.e. somewhere between 0 and 0.002 and not between 1 and 7.
Your data has x values well below 0.01, while your ticks start at 1, so your data will be to the left of the plot. I would suggest using a logarithmic x axis, just like the example below. This will also fix the problem with the x values being of different orders of magnitude. Note that I also put the tick strings in reverse order, assuming that you mistakenly wrote them the other way round. If not, please just go ahead and re-reverse them!
#importing matplotlib to create a graph
import matplotlib.pyplot as plt
x = [1.95e-06, 9.75e-06, 1.95e-05, 9.75e-05, 1.95e-04, 9.75e-04, 1.95e-03]
#ploting out the points while labeling the graph
plt.semilogx(x ,[0.2,0.4,0.6,0.8,1.0,1.2,1.4])
plt.xticks(x, [str('1.95E-03'), str('9.75E-04'), str('1.95E-04'), str('9.75E-05'),str('1.95E-05'), str('9.75E-06'), str('1.95E-06')], rotation=45)
plt.title('Red')
plt.ylabel('Absorption')
plt.xlabel('Concentration')
plt.grid(True)
plt.tight_layout()
plt.savefig('points.png')
plt.show()
The first argument to plt.xticks should be x-coords (not tick indexes).
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.