Search Results

Search found 166 results on 7 pages for 'matplotlib'.

Page 2/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • how to handle an asymptote/discontinuity with Matplotlib

    - by Geddes
    Hello all. Firstly - thanks again for all your help. Sorry not to have accepted the responses to my previous questions as I did not know how the system worked (thanks to Mark for pointing that out!). I have since been back and gratefully acknowledged the kind help I have received. My question: when plotting a graph with a discontinuity/asymptote/singularity/whatever, is there any automatic way to prevent Matplotlib from 'joining the dots' across the 'break'? (please see code/image below). I read that Sage has a [detect_poles] facility that looked good, but I really want it to work with Matplotlib. Thanks and best wishes, Geddes import matplotlib.pyplot as plt import numpy as np from sympy import sympify, lambdify from sympy.abc import x fig = plt.figure(1) ax = fig.add_subplot(111) # set up axis ax.spines['left'].set_position('zero') ax.spines['right'].set_color('none') ax.spines['bottom'].set_position('zero') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # setup x and y ranges and precision xx = np.arange(-0.5,5.5,0.01) # draw my curve myfunction=sympify(1/(x-2)) mylambdifiedfunction=lambdify(x,myfunction,'numpy') ax.plot(xx, mylambdifiedfunction(xx),zorder=100,linewidth=3,color='red') #set bounds ax.set_xbound(-1,6) ax.set_ybound(-4,4) plt.show()

    Read the article

  • Python: x-y-plot with matplotlib

    - by kame
    I want to plot some data. The first column contains the x-data. But matplotlib doesnt plot this. Where is my mistake? #fresnel formula import numpy as np from numpy import cos from scipy import * from pylab import plot, show, ylim, yticks from matplotlib import * from pprint import pprint n1 = 1.0 n2 = 1.5 #alpha, beta, intensity data = [ [10, 22, 4.3], [20, 42, 4.2], [30, 62, 3.6], [40, 83, 1.3], [45, 102, 2.8], [50, 123, 3.0], [60, 143, 3.2], [70, 163, 3.8], ] for i in range(len(data)): rhotang1 = (n1 * cos(data[i][0]) - n2 * cos(data[i][1])) rhotang2 = (n1 * cos(data[i][0]) + n2 * cos(data[i][1])) rhotang = rhotang1 / rhotang2 data[i].append(rhotang) #append 4th value pprint(data) x = data[:][0] y1 = data[:][2] y3 = data[:][3] plot(x, y1, x, y3) show() EDIT: http://paste.pocoo.org/show/205534/ But it doesnt work.

    Read the article

  • Confusion Matrix with number of classified/misclassified instances on it (Python/Matplotlib)

    - by Pinkie
    I am plotting a confusion matrix with matplotlib with the following code: from numpy import * import matplotlib.pyplot as plt from pylab import * conf_arr = [[33,2,0,0,0,0,0,0,0,1,3], [3,31,0,0,0,0,0,0,0,0,0], [0,4,41,0,0,0,0,0,0,0,1], [0,1,0,30,0,6,0,0,0,0,1], [0,0,0,0,38,10,0,0,0,0,0], [0,0,0,3,1,39,0,0,0,0,4], [0,2,2,0,4,1,31,0,0,0,2], [0,1,0,0,0,0,0,36,0,2,0], [0,0,0,0,0,0,1,5,37,5,1], [3,0,0,0,0,0,0,0,0,39,0], [0,0,0,0,0,0,0,0,0,0,38] ] norm_conf = [] for i in conf_arr: a = 0 tmp_arr = [] a = sum(i,0) for j in i: tmp_arr.append(float(j)/float(a)) norm_conf.append(tmp_arr) plt.clf() fig = plt.figure() ax = fig.add_subplot(111) res = ax.imshow(array(norm_conf), cmap=cm.jet, interpolation='nearest') cb = fig.colorbar(res) savefig("confmat.png", format="png") But I want to the confusion matrix to show the numbers on it like this graphic (the right one): http://i48.tinypic.com/2e30kup.jpg How can I plot the conf_arr on the graphic?

    Read the article

  • subplot matplotlib wrong syntax

    - by madptr
    I am using matplotlib to subplot in a loop. For instance, i would like to subplot 49 data sets, and from the doc, i implemented it this way; import numpy as np import matplotlib.pyplot as plt X1=list(range(0,10000,1)) X1 = [ x/float(10) for x in X1 ] nb_mix = 2 parameters = [] for i in range(49): param = [] Y = [0] * len(X1) for j in range(nb_mix): mean = 5* (1 + (np.random.rand() * 2 - 1 ) * 0.5 ) var = 10* (1 + np.random.rand() * 2 - 1 ) scale = 5* ( 1 + (np.random.rand() * 2 - 1) * 0.5 ) Y = [ Y[k] + scale * np.exp(-((X1[k] - mean)/float(var))**2) for k in range(len(X1)) ] param = param + [[mean, var, scale]] ax = plt.subplot(7, 7, i + 1) ax.plot(X1, Y) parameters = parameters + [param] ax.show() However, i have an index out of range error from i=0 onwards. Where can i do better to have it works ? Thanks

    Read the article

  • matplotlib plot window won't appear

    - by user1518837
    I'm using Python 2.7.3 in 64-bit. I installed pandas as well as matplotlib 1.1.1, both for 64-bit. Right now, none of my plots are showing. After attempting to plot from several different dataframes, I gave up in frustration and tried the following first example from http://pandas.pydata.org/pandas-docs/dev/visualization.html: INPUT: import matplotlib.pyplot as plt ts = Series(randn(1000), index=date_range ('1/1/2000', periods=1000)) ts = ts.cumsum() ts.plot() pylab.show() OUTPUT: Axes(0.125,0.1;0.775x0.8) And no plot window appeared. Other StackOverflow threads I've read suggested I might be missing DLLs. Any suggestions?

    Read the article

  • Matplotlib pick event order for overlapping artists

    - by Ajean
    I'm hitting a very strange issue with matplotlib pick events. I have two artists that are both pickable and are non-overlapping to begin with ("holes" and "pegs"). When I pick one of them, during the event handling I move the other one to where I just clicked (moving a "peg" into the "hole"). Then, without doing anything else, a pick event from the moved artist (the peg) is generated even though it wasn't there when the first event was generated. My only explanation for it is that somehow the event manager is still moving through artist layers when the event is processed, and therefore hits the second artist after it is moved under the cursor. So then my question is - how do pick events (or any events for that matter) iterate through overlapping artists on the canvas, and is there a way to control it? I think I would get my desired behavior if it moved from the top down always (rather than bottom up or randomly). I haven't been able to find sufficient enough documentation, and a lengthy search on SO has not revealed this exact issue. Below is a working example that illustrates the problem, with PathCollections from scatter as pegs and holes: import matplotlib.pyplot as plt import sys class peg_tester(): def __init__(self): self.fig = plt.figure(figsize=(3,1)) self.ax = self.fig.add_axes([0,0,1,1]) self.ax.set_xlim([-0.5,2.5]) self.ax.set_ylim([-0.25,0.25]) self.ax.text(-0.4, 0.15, 'One click on the hole, and I get 2 events not 1', fontsize=8) self.holes = self.ax.scatter([1], [0], color='black', picker=0) self.pegs = self.ax.scatter([0], [0], s=100, facecolor='#dd8800', edgecolor='black', picker=0) self.fig.canvas.mpl_connect('pick_event', self.handler) plt.show() def handler(self, event): if event.artist is self.holes: # If I get a hole event, then move a peg (to that hole) ... # but then I get a peg event also with no extra clicks! offs = self.pegs.get_offsets() offs[0,:] = [1,0] # Moves left peg to the middle self.pegs.set_offsets(offs) self.fig.canvas.draw() print 'picked a hole, moving left peg to center' elif event.artist is self.pegs: print 'picked a peg' sys.stdout.flush() # Necessary when in ipython qtconsole if __name__ == "__main__": pt = peg_tester() I have tried setting the zorder to make the pegs always above the holes, but that doesn't change how the pick events are generated, and particularly this funny phantom event.

    Read the article

  • Matplotlib canvas drawing

    - by Morgoth
    Let's say I define a few functions to do certain matplotlib actions, such as def dostuff(ax): ax.scatter([0.],[0.]) Now if I launch ipython, I can load these functions and start a new figure: In [1]: import matplotlib.pyplot as mpl In [2]: fig = mpl.figure() In [3]: ax = fig.add_subplot(1,1,1) In [4]: run functions # run the file with the above defined function If I now call dostuff, then the figure does not refresh: In [6]: dostuff(ax) I have to then explicitly run: In [7]: fig.canvas.draw() To get the canvas to draw. Now I can modify dostuff to be def dostuff(ax): ax.scatter([0.],[0.]) ax.get_figure().canvas.draw() This re-draws the canvas automatically. But now, say that I have the following code: def dostuff1(ax): ax.scatter([0.],[0.]) ax.get_figure().canvas.draw() def dostuff2(ax): ax.scatter([1.],[1.]) ax.get_figure().canvas.draw() def doboth(ax): dostuff1(ax) dostuff2(ax) ax.get_figure().canvas.draw() I can call each of these functions, and the canvas will be redrawn, but in the case of doboth(), it will get redrawn multiple times. My question is: how could I code this, such that the canvas.draw() only gets called once? In the above example it won't change much, but in more complex cases with tens of functions that can be called individually or grouped, the repeated drawing is much more obvious, and it would be nice to be able to avoid it. I thought of using decorators, but it doesn't look as though it would be simple. Any ideas?

    Read the article

  • Matplotlib autodatelocator custom date formatting?

    - by jawonlee
    I'm using Matplotlib to dynamically generate .png charts from a database. The user may set as the x-axis any given range of datetimes, and I need to account for all of it. While Matplotlib has the dates.AutoDateLocator(), I want the datetime format printed on the chart to be context-specific - e.g. if the user is charting from 3 p.m. to 5 p.m., the year/month/day information doesn't need to be displayed. Right now, I'm manually creating Locator and Formatter objects thusly: def get_ticks(start, end): from datetime import timedelta as td delta = end - start if delta <= td(minutes=10): loc = mdates.MinuteLocator() fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(minutes=30): loc = mdates.MinuteLocator(byminute=range(0,60,5)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(hours=1): loc = mdates.MinuteLocator(byminute=range(0,60,15)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(hours=6): loc = mdates.HourLocator() fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(days=1): loc = mdates.HourLocator(byhour=range(0,24,3)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(days=3): loc = mdates.HourLocator(byhour=range(0,24,6)) fmt = mdates.DateFormatter('%I:%M %p') elif delta <= td(weeks=2): loc = mdates.DayLocator() fmt = mdates.DateFormatter('%b %d') elif delta <= td(weeks=12): loc = mdates.WeekdayLocator() fmt = mdates.DateFormatter('%b %d') elif delta <= td(weeks=52): loc = mdates.MonthLocator() fmt = mdates.DateFormatter('%b') else: loc = mdates.MonthLocator(interval=3) fmt = mdates.DateFormatter('%b %Y') return loc,fmt Is there a better way of doing this?

    Read the article

  • Plot numpy datetime64 with matplotlib

    - by enedene
    I have two numpy arrays 1D, one is time of measurement in datetime64 format, for example: array([2011-11-15 01:08:11, 2011-11-16 02:08:04, ..., 2012-07-07 11:08:00], dtype=datetime64[us]) and other array of same length and dimension with integer data. I'd like to make a plot in matplotlib time vs data. If I put the data directly, this is what I get: plot(timeSeries, data) Is there a way to get time in more natural units? For example in this case months/year would be fine.

    Read the article

  • Create matplotlib legend out of the figure

    - by Werner
    I added the legend this way: leg = fig.legend((l0,l1,l2,l3,l4,l5,l6), ('0 Cl : r2, slope, origin', '1 Cl :'+str(r1b)+' , '+str(m1)+' , '+str(b1), '2 Cl :'+str(r2b)+' , '+str(m2)+' , '+str(b2), '3 Cl :'+str(r3b)+' , '+str(m3)+' , '+str(b3), '4 Cl :'+str(r4b)+' , '+str(m4)+' , '+str(b4), '5 Cl :'+str(r5b)+' , '+str(m5)+' , '+str(b5), '6 Cl :'+str(r6b)+' , '+str(m6)+' , '+str(b6), ), 'upper right') but the legend appears inside the plot. How can I tell matplotlib to put it to the right of the plot and at the right?

    Read the article

  • Accented characters in matplotlib

    - by OldJim
    Does anyone know a way to get matplotlib to render accented chars (é,ã,â,etc)? For instance i'm trying to use accented chars on set_yticklabels() and matplot renders squares instead, and when i use unicode() it renders the wrong chars. Is there a way to make this work? Thanks in advance, Jim.

    Read the article

  • matplotlib - changing rect colours on the fly

    - by Nick
    I am playing with matplotlib - I have a bar chart, and I want to highlight the bar which user clicks. I have a callback that goes through a rect collection (the one I got from self.axis.bar(...)) and finds out which one was clicked (looking at the coordinates). At this point I want to call something to change the colour of the current bar. Is it possible? How do I do that?

    Read the article

  • matplotlib equivalent for MATLABs truesize()

    - by Lucas
    I am new to matplotlib and python and would like to display an image so that 1 pixel of the image is actually represented by 1 pixel in the figure. In MATLAB, this is achieved with the command truesize(). How can I do this in Python? I tried playing around with the imshow() arguments as well as set_dpi() and set_figwidth()/set_figheight(), but with no luck. Thanks.

    Read the article

  • unevenly centered subplots in matplotlib in Python?

    - by user248237
    I am plotting a simple pair of subplots in matplotlib that are for some reason unevenly centered. I plot them as follows: plt.figure() # first subplot s1 = plt.subplot(2, 1, 1) plt.bar([1, 2, 3], [4, 5, 6]) # second subplot s2 = plt.subplot(2, 1, 2) plt.pcolor(rand(5,5)) # add colorbar plt.colorbar() # square axes axes_square(s1) axes_square(s2) where axes_square is simply: def axes_square(plot_handle): plot_handle.axes.set_aspect(1/plot_handle.axes.get_data_ratio()) The plot I get is attached. The top and bottom plots are unevenly centered. I'd like their yaxis to be aligned and their boxes to be aligned. If I remove the plt.colorbar() call, the plots become centered. How can I have the plots centered while the colorbar of pcolor is still shown? I want the axes to be centered and have the colorbar be outside of that alignment, either to the left or to the right of the pcolor matrix. image of plots link thanks.

    Read the article

  • draw csv file data as a heatmap using numpy and matplotlib

    - by Schrodinger's Cat
    Hello all, I was able to load my csv file into a numpy array: data = np.genfromtxt('csv_file', dtype=None, delimiter=',') Now I would like to generate a heatmap. I have 19 categories from 11 samples, along these lines: cat,1,2,3... a,0.0,0.2,0.3 b,1.0,0.4,0.2 . . . I wanted to use matplotlib colormesh. but I'm at loss. all the examples I could find used random number arrays. any help and insights would be greatly appreciated. many thanks

    Read the article

  • Create a color generator in matplotlib

    - by Brendan
    I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a spectrum, for example the gist_rainbow map shown here. I have found the following works but it seems very complicated and more importantly difficult to remember, from pylab import * NUM_COLORS = 22 mp = cm.datad['gist_rainbow'] get_color = matplotlib.colors.LinearSegmentedColormap.from_list(mp, colors=['r', 'b'], N=NUM_COLORS) ... # Then in a for loop this_color = get_color(float(i)/NUM_COLORS) Moreover, it does not cover the range of colours in the gist_rainbow map, I have to redefine a map. Maybe a generator is not the best way to do this, if so what is the accepted way?

    Read the article

  • matplotlib: working with range in x-axis

    - by user324333
    Hey Guys, I'm trying to do a basic line graph here, but I can't seem to figure out how to adjust my x axis. And here is the error I get when I try adjusting my range. from pylab import * plot ( range(0,11),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' ) plot ( range(0,11),[12,5,33,2,4,5,3,3,22,10],'o-',label='sample2' ) xlabel('x axis') ylabel('y axis') title('my sample graphs') legend(('sample1','sample2')) savefig("sampleg.png",dpi=(640/8)) show() File "C:\Python26\lib\site-packages\matplotlib\axes.py", line 228, in _xy_from_xy raise ValueError("x and y must have same first dimension") ValueError: x and y must have same first dimension I want my range to be a list of strings: ["12/1/2007","12/1/2008", "12/1/2009","12/1/2010"] Any suggestions?

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >