How can adjust the heatmap in matplotlib?
I have two files with one columns of numbers each one, and I've created a heatmap as you can see in the next figure:
I'm trying to adjust the heatmap that i've created for have a figure like this:
I mean, I want adjust the number of the colorbar between 0 and 1 as the figure above. And, I don't want to have space white on the bord of the axes. So, What is I need to change o add to the script, for doing this?
I'm using the next script. Thanks a lot for your support.
from matplotlib import ticker
import numpy as np
import numpy.random
import matplotlib.pyplot as plt
# Create data
x = open("file1.txt").read().splitlines()
y = open("file2.txt").read().splitlines()
f = np.random.normal(x).astype(np.float)
g = np.random.normal(y).astype(np.float)
# Create heatmap
heatmap, xedges, yedges = np.histogram2d(f, g, bins=(50,50))
extent = [xedges[0], xedges[1], yedges[0], yedges[1]]
#heatmap = plt.pcolor(np.histogram2d(f, g, bins=(100,100), cmap=cmap,norm=norm)
# Plot heatmap
plt.clf()
plt.title('heatmap example')
plt.ylabel('y')
plt.xlabel('x')
plt.imshow(heatmap, cmap='Blues', extent=extent)
cb = plt.colorbar()
tick_locator = ticker.MaxNLocator(nbins=10)
cb.locator = tick_locator
cb.update_ticks()
plt.show()
See also questions close to this topic

How to plot a list of lists against one list
import matplotlib.pyplot as plt V = [[10,20,30,40],[30,40,50,50,70]] # It may consist n lists, each list with m values I = [[1,2,3,4],[3,4,5,6,7]] # It may consist n lists, each list with m values for t in list(zip(V,I)): plt.plot(*t) plt.show()
[Above
V
andI
consists of 2 lists, each list with 4 elements. I want to plotV
andI
in same XY figure. This V and I data is going to have 2 plots. ] 
Wrong chart when plot prices downloaded from Binance
I am trying to download data from Binance and plot, but it gives me weird graph like this. Is it because data has lots of digits after the decimal point? how to reduce it? Also, if I change from 1DAY to 4HOUR I will get 4 hours data right? How can I plot it in Candles?
import json from binance.client import Client import matplotlib.pyplot as plt import pandas as pd import numpy as np client = Client("", "") candles = client.get_historical_klines("BTCUSDT", Client.KLINE_INTERVAL_1DAY, "1 Dec, 2017", "18 Jul, 2018") df = pd.DataFrame(candles,columns= ['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', \ 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', \ 'Can be ignored']) a = df['Close'].iloc[1:10] plt.plot(a) plt.show()

Python : Basemap barbs , wind vector plotting on map
I'm trying to plotting wind vector on map using basemap.barbs.
I try to draw it as a test with simple code.
No error message is shown with this code, Even if I wait, the picture does not come out..
If a picture is being drawn, the picture does not come out even after waiting a long time.
I think there seems to be something else wrong.
It is the first time to draw a wind field with Python, so I'm immature.
Is it because of the high data resolution? (Its len(lon) is 360, len(lat) is 200)
Or is it another matter?
import netCDF4 as nc import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap,addcyclic,shiftgrid data=nc.Dataset('wind.nc','r') lon=data.variables['XU_OCEAN'][:] lat=data.variables['YU_OCEAN'][:] time=data.variables['TIME1'][:] uwind=data.variables['WIND_POWER_U'][:] vwind=data.variables['WIND_POWER_V'][:] uwind_DJF=[] vwind_DJF=[] for i in range(11,20*12+1,12): uwind_DJF.append((uwind[i]+uwind[i+1]+uwind[i+2])/3) vwind_DJF.append((vwind[i]+vwind[i+1]+vwind[i+2])/3) uwind_DJF=np.mean(uwind_DJF,axis=0) ##shape is (200,360) vwind_DJF=np.mean(vwind_DJF,axis=0) ##shape is (200,360) fig=plt.figure(figsize=(12,9)) m=Basemap(resolution='l',projection='cyl',llcrnrlon=90,llcrnrlat=30,urcrnrlon=80,urcrnrlat=70) m.drawparallels(np.arange(90,90,30),labels=[1,0,1,0],fontsize=10) m.drawmeridians(np.arange(180,180,45),labels=[0,0,0,1],fontsize=10) m.drawcoastlines() m.drawstates() m.drawcountries() lon2d,lat2d=np.meshgrid(lon,lat) x,y=m(lon2d,lat2d) m.barbs(x,y,uwind_DJF,vwind_DJF) plt.show()

Extracting a two digit number from a string in python
I need to extract a two digit number from a string in python3.
** e.g. string is "1234" and I want the middle two numbers so I get 23.**
This isn't limited to just four letters, it could be hundreds.
Please could someone help?
Thank you as always!

How to use loop for 14 based number system to calculate the sum and product of user input?
I'm in a heap of trouble here, I'm trying to figure out the code for an assignment. What my professor is asking of us is to find the sum and product of two 14 based number 09, and A, J, Q, and K by user input.
So far I have code to scan the user input, but I am stuck on the for loop part. I was trying to scan each integer and use the algorithm (value = symbol * 14^(digit1)) in a for loop, then add all the number. I don't even know where to start with the product of the two.
An alien species uses 14based numbering system. Their ten digits, 0 >through 9, are the same as our decimal system. They use A, J, Q and K to represent decimal 10, 11, 12 and 13, respectively. They hire you to write a Java program to do the summation of their two numbers. The program should prompt users for two 14based numbers and then display the summation and the product of those two entered 14based numbers. The outputs should also be 14based. (They are unwilling to learn our decimal systems!) For example, if inputs are 17 and 96, their sum and product should be AK and 1020, respectively.
User interface specifications:
Input:
The program prompts users for two 14based numbers.
▪ A 14based number is a string that contains a combination of digit characters and letter characters of A, J, Q and K, case insensitive.
▪ Your program should direct users to input the two numbers, separated by space(s), on the same line.
▪ The data input line is immediately below the prompt message line. In other words, after the prompt message is displayed, your program should force users to enter the two numbers on a new line immediately below the prompt message.
▪ Your program has to check the validity of input numbers. You can assume input numbers neither are negative nor contain a decimal point. o An example of the input session is illustrated as below: Please enter two 14based numbers on next line 17 96
Output:
o Two 14based numbers that are sum and product of the two input 14based numbers.
Those are the instructions, I hope you can help me out on this loop problem, thank you.
import java.util.Scanner; public class H6_Ruby{ public static final int A = 10; public static final int J = 11; public static final int Q = 12; public static final int K = 13; public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("Please enter 2 14based numbers seperated by a space: "); // for digit 1 String based1 = scan.next(); int basedDig1 = based1.length(); int powerDigit1 = basedDig1  1; for (i = basedDig1[1]; i //for digit 2 String based2 = scan.next(); int basedDig2 = based2.length(); int powerDigit2 = basedDig2 1; //unfinished, stuck } }

Is it possible to have a float number without a decimal point in Python?
I asked this because it is possible in R. Note that both 1.5 and 1 are in numeric type (doubleprecision), and only 1L is an integer. When coercing a string into numeric type, it doesn't show a decimal point if there's not one in the string.
class(1.5) # "numeric" class(1) # "numeric" class(1L) # "integer" x < as.numeric("3") x # 3 class(x) # "numeric"
Am I allowed to have similar operations in Python? Let's say I have a function called
key_in_a_number
:def key_in_a_number(): num = input("Key in a number here: ") try: return float(num) except ValueError: return "Please key in only numbers."
Now if one keys in "40", it will return 40.0, but 40.0 and 40 are different in certain digits. Thus, 40 should be returned if "40" is keyed in, while 40.0 should be returned only when "40.0" is keyed in.
My work around is:
def key_in_a_number(): num = input("Key in a number here: ") try: return int(num) except ValueError: try: return float(num) except ValueError: return "Please key in only numbers."
However, in this way, I cannot be sure that the results are always in the same type, which could be problematic in following data storage or processing. Is there any way to have a number in float type without a decimal point?

Overlaying plots on a single graph
I have two heatmaps which are based on 2d histograms that I am trying to overlay on a single graph. The limits of their axes (extent_L and extent_H) do not necessarily coincide exactly. I can make the individual plots satisfactorily if needed, but when trying to show both heatmaps on a single graph nicely, only the most recent one is displayed.
import numpy as np import numpy.random import matplotlib.pyplot as plt # Generate some test data x_L = np.random.randn(8873) y_L = np.random.randn(8873) x_H = np.random.randn(1000) y_H = np.random.randn(1000) heatmap_L, xedges_L, yedges_L = np.histogram2d(x_L, y_L, bins=50) extent_L = [xedges_L[0], xedges_L[1], yedges_L[0], yedges_L[1]] heatmap_H, xedges_H, yedges_H = np.histogram2d(x_H, y_H, bins=50) extent_H = [xedges_H[0], xedges_H[1], yedges_H[0], yedges_H[1]] plt.clf() im1 = plt.imshow(heatmap_L.T, extent=extent_L, origin='lower', cmap='Blues') im2 = plt.imshow(heatmap_H.T, extent=extent_H, origin='lower', cmap='Greens') plt.show()
Edit: If I'm not mistaken, all points are not in exactly the proper location
import numpy as np import numpy.random import matplotlib.pyplot as plt # Generate some test data x_L = np.random.randn(8873) y_L = np.random.randn(8873) x_H = np.random.randn(1000) y_H = np.random.randn(1000) heatmap_L, xedges_L, yedges_L = np.histogram2d(x_L, y_L, bins=50) extent_L = np.array([xedges_L[0], xedges_L[1], yedges_L[0], yedges_L[1]]) heatmap_H, xedges_H, yedges_H = np.histogram2d(x_H, y_H, bins=50) extent_H = np.array([xedges_H[0], xedges_H[1], yedges_H[0], yedges_H[1]]) plt.clf() im1 = plt.imshow(heatmap_L.T, extent=extent_L, origin='lower', cmap='Blues') im2 = plt.imshow(heatmap_H.T, extent=extent_H, origin='lower', cmap='Greens') plt.autoscale() plt.show()
flatHMH = np.reshape(heatmap_H, 2500) # flatten the 2D arrays flatHML = np.reshape(heatmap_L, 2500) maxHMH = flatHMH.max() # Find the maximum in each maxHML = flatHML.max() # Now for each value in the flat array build an RGBA tuple using # 1 for the colour we want  either green or blue, and then scaling # the value by the maximum, finally reshaping back to a 50x50 array augHMH = np.array([(0, 1, 0, x/maxHMH) for x in flatHMH]).reshape((50, 50, 4)) augHML = np.array([(0, 0, 1, x/maxHML) for x in flatHML]).reshape((50, 50, 4)) plt.clf() # Plot without cmap as colours are now part of the data array passed. im1 = plt.imshow(augHML, extent=extent_L, origin='lower') im2 = plt.imshow(augHMH, extent=extent_H, origin='lower') plt.autoscale() plt.show()
If you look closely at the points in the last plot, for example the clustering of points at the edge, you'll notice they are not the same as in the plot above.

Error formatting matplotlib heat map annotations
I am trying to format annotations on my matplotlib heatmap. Here is the code I have.
x_axis_titles = ["Recession Probibility"] spread = array([[3.0], [5.0], [10.0], [15.0], [20.0], [25.0], [30.0], [40.0], [50.0], [60.0], [70.0], [80.0], [90.0]]) spread_divisions = [1.35, 1.21, 0.76, 0.46, 0.22, 0.02, 0.17, 0.50, 0.82, 1.13, 1.46, 1.85, 2.40] f = Figure(dpi=100) ax = f.add_subplot(1,1,1) ax.imshow(spread, cmap="bwr") f.set_figwidth(3, forward=True) f.set_figheight((root.winfo_height() / 100)  4.0, forward=True) ax.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False) ax.set_yticks(arange(len(spread_divisions))) ax.set_yticklabels(spread_divisions) for i in range(len(spread)): for j in range(len(x_axis_titles)): ax.text(j, i, '%.1f%' % spread[i, j], ha="center", va="center", color="w") ax.set_title("Recession Probability\n\nCurrent Spread: " + str(round(dcf_data[9][1]  (dcf_data[8][1] * 100), 2))) canvas = FigureCanvasTkAgg(f, master=dashboard_page) canvas.show() canvas.get_tk_widget().grid(row=1, column=0, columnspan=2, sticky=tkinter.W, padx=(10), pady=(5,5))
However I am receiving this error:
ValueError: incomplete format
which comes from the lineax.text(j, i, '%.1f%' % spread[i, j], ha="center", va="center", color="w")
within the nested for loop.I am trying to add percent symbols to the text within the heatmap pictured below.
Any help is appreciated! Thank you.

Show more than 20 categories on highcharts heatmap xaxis
I am working with Highcharts heatmaps. I have multiple data points (I am calling them functions), each having some data series defined as
The format of the above is
string, epochtime, value
The series1 or series2 (you see above) are series names associated with each function. I want to update the series in the chart based on the click of a button associated with a function. There are multiple such functions and each function has its own button. Clicking on the button populates the respective data in the heatmap using the above array of arrays.
Th problem is when I click on adding a function which has more than 20 series defined in the format above , it doesn’t work . The screen displays time since 1970(for some reason). While it works for less than 20 series.

Use the same colorbar for different subplots with differents ranges
I have this graphs Subplot and I need only one colorbar for all subplots, this question is already answered for plots with the same ranges but my problem is all the 'data matrices' has different ranges, some negative, and other not. How to do this? Thanks in advance.

Python  plotting blocks of curves in shades of different colours
I have four data files, which are made of a few columns each. These data files are called
tomo6, tomo4, tomo2
(made of many columns) and spline2 (only one column). I want to plotimport matplotlib.pyplot as plt ### the ratio of the first column of tomo6, tomo4 and tomo2 w.r.t spline2 plt.loglog(tomo6[0]/spline2) plt.loglog(tomo4[0]/spline2) plt.loglog(tomo2[0]/spline2) ### the ratio of the second column of tomo6, tomo4 and tomo2 w.r.t spline2 plt.loglog(tomo6[1]/spline2) plt.loglog(tomo4[1]/spline2) plt.loglog(tomo2[1]/spline2) ### the ratio of the third column of tomo6, tomo4 and tomo2 w.r.t spline2 plt.loglog(tomo6[2]/spline2) plt.loglog(tomo4[2]/spline2) plt.loglog(tomo2[2]/spline2)
and so on for all the columns.
My question regards the colours that get assigned to these plots. Ideally, I would like to plot these curves in such a way that:
1) I can recognise the 'blocks', i.e. the three curves concerning the first column, the three curves concerning the second column, the three curves concerning the third column and so on
2) Point 1 would be easily achieved by assigning to the 'blocks' different colours, e.g. red for the first columncurves, blue for the second columnones and green for the third columncurves. But I also need to be able to distinguigh, within each block, what is the curve pertaining to
tomo6, tomo4
andtomo2
. This can be achieved by assigning different shades of the same colour to the three curves within one block: e.g., from darker to lighter versions of red for the curves of the first oclumn oftomo6, tomo4, tomo2
.I could easily achieve point 2 by setting manually these colours, However, I would like to ask if there are moer clever and less manual ways of accomplishing this, since in principle the number of columns in the files can be large, so doing this manually could be cumbersome.
Also, if there are better suggestions on how to plot efficiently the curves, they are welcome. In any case I would like to obtain a colour bar, at the end, which is easy to understand for the reader, so that he can easily recognise to which file the curves belong to, given their colour.

Matplotlib, one colorbar for all subplots, overlay on papersize
I´ve got the following problem, that my colorbar overlays my papersized subplots that are "printed" as an pdf.
Code example:
import numpy as np import matplotlib.pyplot as plt import pandas as pd if __name__ == '__main__': titles = np.random.uniform(low=1, high=11, size=(1,10)) temp = np.random.uniform(low=23, high=200, size=(10,10)) ctf0102 = np.random.uniform(low=23, high=200, size=(10,10)) ctf03 = np.random.uniform(low=23, high=200, size=(10,10)) fig = plt.figure(figsize=(11.69,8.27), dpi=100) for num in range(len(titles)): ax = fig.add_subplot(3,4,num) im = ax.scatter(ctf03[1:,num], ctf0102[:,num], 12, temp[:,num], cmap='magma') ax.set_title(titles[num]) fig.text(0.5, 0.00, '...', ha='center', fontsize=16) fig.text(0.00, 0.5, '...', va='center', rotation='vertical', fontsize=16) cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(im, cax=cbar_ax) plt.tight_layout(pad=2) fig.savefig("example.pdf", dpi=fig.dpi, bbox_inches='tight', pad_inches=0.3)
Any idea how i can move the colorbar to the right, by resizing the space of all my subplots? Besides that i would like to enlarge the colorbar, to become a smooth closing with the top and bottom of all subplots.
Thanks for help and ideas.