Not able to generate the correct graph in Python - python

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.

Related

How to show all the labels in matplotlib?

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.

How do I use mathlibplot.hist with x and y values using bins=40 in Python 3?

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!

Setting colour scale to log in a contour plot

I have an array A which I have plotted in a contour plot using X and Y as coordinate axes,
plt.contourf(X,Y,A)
Problem is, the values in A vary from 1 to a very large number such that the color scale doesn't show a plot. When I plot log(A), I get the following contour,
which is what I'm looking for. But I want to be able to view the values of the array A, instead of log(A), when I hover my cursor over a certain (X,Y) point. I already got an answer for how to do that, but how would I go about doing it while my colour scale remains log? Basically what I'm trying to do is to make the color scale follow a log pattern, but not the array values themselves.
Thanks a lot!
You can do this:
from matplotlib import colors
plt.contourf(X, Y, A, norm=colors.LogNorm())
plt.colorbar()
plt.show()
or
from matplotlib import ticker
plt.contourf(X, Y, A, locator=ticker.LogLocator())
plt.colorbar()
plt.show()
A similar question was already asked for log-scaling the colors in a scatter plot: A logarithmic colorbar in matplotlib scatter plot
As is it was indicated there, there is an article in matplotlibs documentation that describes norms of colormaps: http://matplotlib.org/devdocs/users/colormapnorms.html
Essentially, you can set the norm of your contourplot by adding the keyword , norm=matplotlib.colors.LogNorm()

How do I set the size of the axes patch so that the plot labels aren't clipped (matplotlib)

I have a graph in which I've set the axis labels to scientific notation using
formatter = mpl.ticker.FormatStrFormatter('%4.2e')
axis2.yaxis.set_major_formatter(formatter)
However, the axes.patch (or whatever is the right way to express the 'canvas' extent of the plot) doesn't adjust so the tick labels and axis label are clipped:
How do I adjust the extent of the axes portion of the plot. Changing the page size (figsize = ...) doesn't do it, since that just scales the overall plot area, resulting in the same clipping problem.
You can use the method tight_layout, which will accommodate the plot in the figure available space.
Example
from pylab import *
f = figure()
f.add_subplot(111)
f.tight_layout()
show()
Hope it helps.
Cheers
Just call fig.tight_layout() (assuming you have a Figure object defined).

rotating xticks causes the ticks partially hidden in matplotlib

I am creating a plot with names on x axis and time values(minutes) on y axis.The names on x axis are like
['cooking']18:15:27 ,['study']18:09:19,['travel']18:21:34` etc ..
where as the y values are 5,1,1 etc.I have given xlabel as 'categories' and ylabel as 'durations in minutes'.
Since the xticks were strings of some length,I decided to rotate them by 90 to avoid overlapping.Now ,the ticks are partially hidden and the xlabel has disappeared.
Is there some way I can make the whole plot accommodate everything..?
thanks
mark
here is the code snippet
import matplotlib.pyplot as plt
...
figure = plt.figure()
barwidth = 0.25
ystep = 10
plt.grid(True)
plt.xlabel('categories')
plt.ylabel('durations in minutes')
plt.title('durations for categories-created at :'+now)
plt.bar(xdata, ydata, width=barwidth,align='center')
plt.xticks(xdata,catnames,rotation=90)
plt.yticks(range(0,maxduration+ystep,ystep))
plt.xlim([min(xdata) - 0.5, max(xdata) + 0.5])
plt.ylim(0,max(ydata)+ystep)
figure.savefig("myplot.png",format="png")
plt.tight_layout()
But be sure to add this command after plt.plot() or plt.bar()
One good option is to rotate the tick labels.
In your specific case, you might find it convenient to use figure.autofmt_xdate() (Which will rotate the x-axis labels among other things).
Alternatively, you could do plt.setp(plt.xticks()[1], rotation=30) (or various other ways of doing the same thing).
Also, as a several year later edit, with recent versions of matplotlib, you can call fig.tight_layout() to resize things to fit the labels inside the figure, as #elgehelge notes below.
Setting the bounding box when saving will also show the labels:
figure.savefig('myplot.png', bbox_inches='tight')

Categories

Resources