python-2.7,csv,matplotlib,graphing

You are looking for set_xticklabels

Based on an answer for modifying tick labels I came up with a solution, don't know whether it will work in your case as your code snippet can't be executed in itself. The idea is to force the tick labels to a .5 spacing, then replace every .5 tick with...

I think the problem here is that you are trying to plot a scatter graph against a non-numeric series. That will fail - although the error message you are given is so misleading that it could be considered a bug. You could, however, explictly set the xticks to use one...

Question 1 I think you've shown for yourself that the commands are not wholly equivalent and just want some reassurance of this. To do what you want to do - you can pass in projection to the add_subplot() calls that are used 'under the covers' by setting up a dictionary...

I believe the colormap is renormalizing to your data. Passing values that range from 0 to 1 gives a colormapping of white:0, blue:0.333, red:0.666, purple:1.0. You can prevent this behavior by passing vmin and vmax to the plot. plt.imshow(dat2, interpolation='none', aspect='auto', origin='upper', cmap=cmap, vmin=0, vmax=4) (I don't have python running...

I think you've gotten slightly mixed up on what the cmap argument is supposed to be. It's either a colormap object (e.g. plt.cm.coolwarm) or the name of a colormap (e.g. "coolwarm"). You're trying to pass in explicit colors. (The [ 0.53800422 0.67490159 0.99172189 1.] is the red, green, blue, and...

As outlined in the documentation the rc file has no .py extension: On Linux, it looks in .config/matplotlib/matplotlibrc [...] On other platforms, it looks in .matplotlib/matplotlibrc. In fact it does not have python syntax but rather uses a yaml-like dictionary structure. So it is likely that matplotlib does not use...

You could set the alpha of the surface to something less than 1 so that its opaqueness can not totally obscure the red dot: ax.plot_surface(WH, WP, Z, rstride=4, cstride=4, cmap=cm.coolwarm, alpha=0.5) ...

You need to capture the artist created by the hlines call: fig, ax = plt.subplots() arts = ax.hlines([.5, .75], 0, 1, lw=5) Which returns a LineCollection object. You can programtically modify it arts.set_color(['sage', 'purple']) and to get the window to update you will need to call fig.canvas.draw() (this last bit...

I think you units[4] data may contain some newline characters (\n) which are causing the strange legend format. If you setup the legend and units strings manually, you get what looks like correct formatting, import numpy as np import matplotlib.pyplot as plt raw = np.random.random((20,5)) legends = [" ", "CH1...

I have tried the following and that works: def testColourMap(cmap): sp = SubplotParams(left=0., bottom=0., right=1., top=1.) fig = Figure((2.5,.2), subplotpars = sp) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) ax.imshow(gradient, aspect=10, cmap=cmap) ax.set_axis_off() canvas.draw() size = canvas.size() width, height = size.width(), size.height()...

I guess, there are twice as many ax.yaxis.get_ticklines() than there are ax.yaxis.get_ticklabels(), so zip just stops before painting them all, while individual loops are fine. This behaviour of zip is explained in the Python documentation....

You have given line2D (x1, y1), (x2, y2), but you need to give it (x1, x2), (y1, y2) line = matplotlib.lines.Line2D((-2.33,4.33),(10,-10.0)) ...

python,matplotlib,data-visualization

Both @tom and @Joe Kington are right: this has been asked before. However, I tried to make an example with slighty less efforts as the linked answers. To use a colormap (which always maps values from [0,1] to color), you first need to normalize your data. For that you can...

As outlined in the documentation you can use ax = pyplot.gca() ax.get_xaxis().get_major_formatter().set_useOffset(False) ...

Here is an example to do it. import numpy as np import pandas as pd import matplotlib.pyplot as plt # simulate some artificial data x = np.random.randn(1000,) y = 5 * x ** 2 + np.random.randn(1000,) data = pd.DataFrame(0.0, columns=['X', 'Y'], index=np.arange(1000)) data.X = x data.Y = y # now...

Your small data set script is largely correct, but with some minor errors. You are missing the if i=='date': continue line. (The source of your 'not comparable' error). In your post, your else line is mis-indented. Possibly (only possibly) you need a call to plt.hold(True) to prevent the creation of...

Maybe not exactly what you are looking for, but tripcolor function is designed for this use case (value defined at triangle centroid) See for instance: http://matplotlib.org/examples/pylab_examples/tripcolor_demo.html...

@jeanrjc's solution almost gets you there, but it adds a completely unnecessary white triangle, which will hide other objects as well (see figure below, version 1). This is a simpler approach, which only adds a polygon of the arc: Basically we create a series of points (points) along the edge...

This does more or less what you want: from __future__ import division import matplotlib.pyplot as plt import numpy as np def plot_ticks(start, stop, tick, n): r = np.linspace(0, 1, n+1) x = start[0] * (1 - r) + stop[0] * r x = np.vstack((x, x + tick[0])) y = start[1]...

python,csv,matplotlib,plot,genfromtxt

I think if you set usemask =True in your genfromtxt command, it will do what you want. Probably don't want filling_values set either arr = np.genfromtxt('DemoData.csv', delimiter=',', dtype=None, missing_values='', usemask=True) you can then plot using something like this: for n in range (1,len(names)): plot(arr[1:,0][logical_not(arr[1:,n].mask)], arr[1:,n].compressed()) ...

Indeed, as Andreus correctly answered, %.1e would give you what I would understand as scientific formatting of the tick values as printed on the axes. However, setting a FormatStrFormatter switches off what is called the scientific formatting feature of the default formatter, where the exponent is not formatted with each...

python,math,numpy,matplotlib,scipy

In this case, you might be better of using Sympy, which allows you to obtain the closed form solutions: from IPython.display import display import sympy as sy from sympy.solvers.ode import dsolve import matplotlib.pyplot as plt import numpy as np sy.init_printing() # LaTeX like pretty printing for IPython t = sy.symbols("t",...

As the documentation states fill_between returns a PolyCollection instance. Collections are stored in ax.collections. So ax.collections.pop() should do the trick. However, I think you have to be careful that you remove the right thing, in case there are multiple objects in either ax.lines or ax.collections. You could save a reference...

python,python-2.7,matplotlib,annotations

In plt.annotate(...), xy gives the position of the data you want to point at (one end of the arrow) and xytext gives the position of your text. In your code, they are overlapping because you specified the same positions for xy and xytext. Try this instead (for example): plt.annotate(df.iloc[pqr,0]+', (%.2f,...

The documentation outlines that you have to use the edge_labels argument to specify custom labels. By default it the string representation of the edge data is used. In the example below such a dictionary is created: It has the edge tuples as keys and the formatted strings as values. To...

There is a Canopy feature of the Package Manager where it knows that the package is installed but does not use it. This means that if you try to install or upgrade pillow for the Canopy terminal it will not be able to do anything. To give access to pillow...

You can use plt.tick_params(axis='y', which='minor') to set the minor ticks on and format them with the matplotlib.ticker FormatStrFormatter. For example, import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter x = np.linspace(0,4,1000) y = np.exp(x) plt.plot(x, y) ax = plt.gca() ax.set_yscale('log') plt.tick_params(axis='y', which='minor') ax.yaxis.set_minor_formatter(FormatStrFormatter("%.1f")) plt.show() ...

python-2.7,matplotlib,plot,interactive

For interactive graphics, you should look into Bokeh (http://bokeh.pydata.org/en/latest/docs/quickstart.html). You can create a slider that will bring up the time slices you want to see.

to get the xticks on the integer values which I think you want, you can set xticks just before you set the xticklabels You can use your x_range to do this: ax.set_xticks(x_range) ...

python,data,matplotlib,analysis

This seems like it would be a lot simpler using a Pandas dataframe. Then, part of your problem is analogous to this question: Read multiple *.txt files into Pandas Dataframe with filename as column header import pandas as pd import matplotlib.pyplot as plt filelist = ['data1.txt', 'data2.txt'] dataframe = pd.concat([pd.read_csv(file,...

python,csv,matplotlib,graph,plot

you need to turn x and y into type np.array before you calculate above_threshold and below_threshold, and then it works. In your version, you don't get an array of bools, but just False and True. I added comma delimiters to your input csv file to make it work (I assume...

python,numpy,matplotlib,plot,instance

Since Calculations is a class, this line invokes the implicit constructor: self.myPlotData = file2.Calculations(*user info*) And you should know that the result of a constructor is an instance of the class. Which is exactly why you are getting that type information. If you actually want myPlotData to be an array,...

You could use where=np.array(y)>0 to restrict where the filled region will be drawn and use interpolate=True to have fill_between find the points of intersection: import numpy as np import matplotlib.pyplot as plt x = np.array([1,2,3,4,5]) y = np.array([0,2,-3,4,-5]) plt.plot(x,y) plt.fill_between(x, 0, y, where=y>0, interpolate=True) plt.show() yields ...

python,numpy,matplotlib,graph,plot

You can use the condition z=='some tag' to index the x and y array Here's an example (based on the code in your previous question) that should do it. Use a set to automate the creation of tags: import csv import datetime as dt import numpy as np import matplotlib.pyplot...

python,matplotlib,scatter-plot,polar-coordinates

The problem is that you're only converting the edges of the array. By converting only the x and y coordinates of the edges, you're effectively converting the coordinates of a diagonal line across the 2D array. This line has a very small range of theta values, and you're applying that...

To install pip on windows, follow this answer. And then you run pip from the command prompt like pip install six, or maybe pip.exe install six as other answer states. You can also just type pip (pip.exe?)into the command prompt terminal to get some helpful pip info....

As rth suggested, define x1 = np.linspace(0, 1, 1000) x2 = np.linspace(0, 1, 100) and then plot raw versus x1, and smooth versus x2: plt.plot(x1, raw) plt.plot(x2, smooth) np.linspace(0, 1, N) returns an array of length N with equally spaced values from 0 to 1 (inclusive). import numpy as np...

The reason that nothing is updating is that you're trying to use pyplot methods for a figure that's not a part of the pyplot state machine. plt.draw() won't draw this figure, as plt doesn't know the figure exists. Use fig.canvas.draw() instead. Regardless, it's better to use fig.canvas.draw() that plt.draw(), as...

You need to unstack your results: df.groupby(['tags_0', 'gender']).gender.count().unstack().plot(kind='barh', legend=False, color=['r', 'g', 'b']) I don't have your data, so just used a value of one for each tag/gender combo....

You could try the following to position your ellipses: choose an x-coordinate and calculate the height of the ellipse necessary to enclose the provided list of functions at that coordinate. import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Ellipse x = np.linspace(1,10,1000) flogs = [lambda x, a=a:...

As shown in this answer, if you name your colorbars (here I used cb1,cb2,cb3), you can set the tick params thusly: cb1=plt.colorbar(i1,ax=ax1,ticks=[U.min(),(U.min()+U.max())/2., U.max()],fraction=0.046, pad=0.04,format='%.2f') cb2=plt.colorbar(i2,ax=ax2,fraction=0.046, pad=0.04,ticks=[UU.min(),(UU.min()+UU.max())/2.,UU.max()],format='%.2f') cb3=plt.colorbar(i3,ax=ax3,fraction=0.046, pad=0.04,ticks=[resU.min(), (resU.min()+resU.max())/2.,resU.max()],format='%.2f') cb1.ax.tick_params(labelsize=6)...

python,matplotlib,plot,google-visualization,heatmap

you need to set the origin of both the imshow instances. But, you also need to change the yedges around in your extent implot = plt.imshow(im,origin='upper') ... extent = [xedges[0], xedges[-1], yedges[-1], yedges[0]] plt.imshow(heatmap, extent=extent,alpha=.5,origin='upper') ...

You need to change the setting in setting file, you can get the current setting file path by following code: import matplotlib as mpl print mpl.matplotlib_fname() if the file is in mpl-data folder, then copy it to user setting folder by following code: import shutil shutil.copy(mpl.matplotlib_fname(), mpl.get_configdir()) then restart you...

r,matlab,matplotlib,gnuplot,matlab-figure

It is not clear whay you want to have. Here a scatter plot using ggplot2. ## some reproducible data set.seed(1) dat <- data.frame( x = round(runif(200,-30,30),2), y = round(runif(200,-2,30),2), msd = sample(c(0,2,3),200,rep=T)) ## scatter plot where the size/color of points depends in msd library(ggplot2) ggplot(dat) + geom_point(aes(x,y,size=msd,color=msd)) + theme_bw() ...

The problem is that you create two legends. You get nicer results with only one. For that you need to store the line artists: l1, = plot.plot(time, pressure, label=r'\textit{Raw}') # ... l2, = ax2.plot(time, needle_lift, label=r'\textit{Needle lift}', color='#4DAF4A') And then you can use them to create the legend, by supplying...

see the following documentation for set_ylim and set_xlim http://matplotlib.org/api/axes_api.html?highlight=set_xlim d = pd.DataFrame(pd.Series(range(10))*2) a = d.plot(style = "o-") a.set_axis_bgcolor('g') a.set_ylim([-1,19]) a.set_xlim([-1,11]) a.margins(.05) ...

python,matplotlib,plot,3d,surface

Even if I agree with the others that meshgrids are not difficult, still I think that a solution is provided by the Mayavi package (check the function surf) from mayavi import mlab mlab.surf(Z) mlab.show()...

I have two options you might want to look at. First, set the axis location and size yourself as such: # your imports and data above fig = plt.figure() ax0a = fig.add_axes([0.1, 0.1, 0.8, 0.25]) ax0b = fig.add_axes([0.1, 0.39, 0.8, 0.25], sharex=ax0a) ax0c = fig.add_axes([0.1, 0.68, 0.8, 0.25], sharex=ax0a) ax0a.set_xticklabels([])...

python-2.7,matplotlib,computer-science,floating-point-conversion

You can't append to a tuple at all (tuples are immutable), and extending to a list with + requires another list. Make curveList a list by declaring it with: curveList = [] and use: curveList.append(curve) to add an element to the end of it. Or (less good because of the...

I'm still using matplotlib 1.2.1 so I'll tell you what works for me. I find that if I pass the line objects to legend(), I also have to pass the labels separately. [This is also consistent with the matplotlib documentation on legened()]. I've modified your example slightly to do this,...

python-3.x,matplotlib,histogram

with your data, cases = list(set(actions)) fig, ax = plt.subplots() ax.hist(map(lambda x: times[actions==x], cases), bins=np.arange(min(times), max(times) + binwidth, binwidth), histtype='bar', stacked=True, label=cases) ax.legend() plt.show() produces ...

python,matplotlib,imagemagick,animated-gif

Update Please read the original answer below before doing anything suggested in this update. If you want to debug this in some depth, you could separate the ImageMagick part out and identify for sure where the issue is. To do that, I would locate your ImageMagick convert program like this:...

When you close the image displayed by plt.show(), the image is closed and freed from memory. You should call savefig and savetxt before calling show. ...

I may be misunderstanding the question, but it sounds like you're wanting something along these lines: import matplotlib.pyplot as plt # Using this layout to make the grouping clear data = [('apples', [0.1, 0.25]), ('oranges', [0.6, 0.35]), ('pears', [0.1, 0.18]), ('bananas', [0.7, 0.98]), ('peaches', [0.6, 0.48])] # Reorganize our data...

python,python-2.7,matplotlib,memory-leaks,tkinter

I'm gonna guess this is caused by the pyplot figure not being destroyed when the Tkinter window is closed. Like in the embedding in tk example try using Figure: from matplotlib.figure import Figure self.__fig = Figure(figsize=(16,11)) example use: import Tkinter as tk import matplotlib matplotlib.use('TkAgg') from matplotlib.figure import Figure from...

So, to get to the color of pixels, you have to look at how matplotlib maps the scalar values of the pixels to colors: It is a two step process. First, a normalization is applied to map the values to the interval [0,1]. Then, the colormap maps from [0,1] to...

python,matplotlib,annotations,imshow

Q: But i dont know how to modify the number of significant digits. A: Pre-process the value to be displayed round( 1.234567890123456e-2, 5 )...

python,numpy,matplotlib,graph,physics

Fixed Equation def E(wt, Q): return np.exp(-x/float(Q)) * ( 1. - (1./2./float(Q))*np.sin(2.* x) ) Your original equation def E(wt, Q): return (np.e**(-x/Q))*(1-(1/2*Q)*np.sin(2*x)) Errors Unused Variables You never use wt BODMAS You don't have a decay parameter set up correctly, so it will oscillate too much. (1/2*Q) when you mean (1/2/Q)...

Try acceleration = params[['accX', 'accY', 'accZ']].plot(ax=acceleration) #rest of code You can pass an axis to df.plot, which handles legends pretty well, and it returns the same axis which you can further manipulate. Another way would be acceleration.plot(params[['accX', 'accY', 'accZ']]) acceleration.legend(['X', 'Y', 'Z']) ...

You might want to add this line to the end of your script: plt.ylim(min(y_pos)-1, max(y_pos)+1) This will reduce the margins to a half-a-bar width....

If you want to animate your figures, you can use matplotlib.animation library. Here is what your code would look like: import matplotlib.pyplot as plt import time import matplotlib.animation as animation fig = plt.figure() ax = fig.add_subplot(111) line, = ax.plot([],[]) ax.set_xlim(3) ax.set_ylim(3) line.set_data([1,2,3],[1,2,3]) def init(): """ Initializes the plots to have...

python,numpy,matplotlib,draw,imshow

You seem to be missing the limits on the y value in the histogram redraw in update_data. The high index and low index are also the wrong way around. The following looks more promising, Z, xedges, yedges = np.histogram2d(x[high_index:low_index],y[high_index:low_index], bins=150) (although I'm not sure it's exactly what you want) EDIT:...

1) what you are looking for is most probably some combination of get_yticks() and set_yticks: plt.yticks(fig.get_yticks(), fig.get_yticks() * 100) plt.ylabel('Distribution [%]', fontsize=16) Note: as mwaskom is commenting times 10000 and a % sign is mathematically incorrect. 2) you can specify where you want your ticks via the xticks function. Then...

You use ticker.FormatStrFormatter('%0.0e'). This formats each number with the string format %0.0e which represents floats using exponential notation: import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker x = np.linspace(1, 40, 100) y = np.linspace(1, 5, 100) # Actually plot the exponential values fig, ax = plt.subplots()...

You could use .rename(): pv_test_A.loc[:,[2015]].rename(columns={2015: "New Label A"}).plot(ax=axes) pv_test_B.loc[:,[2015]].rename(columns={2015: "New Label B"}).plot(ax=axes) The underlying data is preserved, but the columns to be plotted are given a different label for plotting purposes....

I am also new here, so I will try to help as much as I can. Solution which was logical for me is to give index for your circles. Any time you move a circle your class calls function button_release_event as much circles as you have. So, when it comes...

python,matplotlib,legend,scatter-plot

You can set the legend colors as such: import numpy as np import matplotlib.pyplot as plt t = np.linspace(0,10,100) x = np.random.rand(100,3) y = np.random.rand(100,3) colmaps = ['Blues', 'Greys', 'Reds'] for i in range(3): plt.scatter(x[:,i], y[:,i], c=t, cmap=colmaps[i], label=i) plt.legend() ax = plt.gca() legend = ax.get_legend() legend.legendHandles[0].set_color(plt.cm.Blues(.8)) legend.legendHandles[1].set_color(plt.cm.Greys(.8)) legend.legendHandles[2].set_color(plt.cm.Reds(.8)) plt.show()...

You can place Ellipse patches directly onto your axes, as demonstrated in this matplotlib example. To adapt it to use eccentricity as your "third dimension") keeping the marker area constant: from pylab import figure, show, rand from matplotlib.patches import Ellipse import numpy as np import matplotlib.pyplot as plt N =...

The way I have managed to solve this issue has been to use Qt4 as the matplotlib backend. Simply add the following two lines of code after importing matplotlib. import matplotlib as mpl mpl.rcParams['backend'] = "qt4agg" mpl.rcParams['backend.qt4'] = "PySide" This is what I do on Python 3 and have no...

The simplest answer: Use the latex mode: import numpy as np import matplotlib.pyplot as plt plt.rcParams['text.usetex'] = True x = np.arange(10000, 10011) plt.plot(x) plt.show() Result: EDIT: Actually you don't need to use latex at all. The ScalarFormatter which is used by default has an option to use scientific notation: import...

Yes, you assumption was right: You have to set the locator and formatter manually. The "regular" ones are available in matplotlib.ticker and the ones related to dates in matplotlib.dates. There is quite a variety of fixed ones (e.g. WeekdayLocator, MicrosecondLocator, etc.), but also the automatic ones that you get when...

It's not, to me, exactly clear what you want, but here is an example with superimposed imshow plots. fig, axes = plt.subplots(nrows=1, ncols=3) rand1=np.random.random((2000,500)) ax1 = plt.subplot(131) ax1.imshow(rand1) box=np.zeros_like(rand1) box[100:400,100:400]=1 ax1.imshow(box,cmap='Greys',alpha=0.6) Perhaps you need to make sure you have the right subplot selected. e.g. ax3 = plt.subplot(131) for your third...

python,pandas,matplotlib,histogram

This is what you are after... I have added plt.ion() to bring it into interactive mode and plt.draw() to add each figure as you define it. By doing this it becomes obvious that the axis is defined as (y,x) not (x,y)... This reference might also help in the future import...

I found that I can switch the place of the secondary y axis, so the secondary y axis is plotted on the left and the primary on the right: ax2 = ax1.twinx() p1 = ax2.plot(ind, total_facilities, '--bo') p2 = ax1.bar(ind, pdb_facilities, width, color='gray',edgecolor = "none") plt.xlim([-1,len(total_facilities)]) ax2.set_yscale('symlog') ax1.yaxis.tick_right() ax2.yaxis.tick_left() plt.show()...

This will remove the tick labels on the vertical axis in the middle and right plots (which I think is what you mean when you say 'remove the number "pixels"'): ax2.set_yticklabels([]) ax3.set_yticklabels([]) ...

Take this for a starter code : import numpy as np import matplotlib.pyplot as plt from sqlalchemy import create_engine import _mssql fig = plt.figure() ax = fig.add_subplot(111) engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test') connection = engine.connect() result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id') ## the data data =...

python,opencv,numpy,matplotlib,ransac

OpenCV use NumPy ndarray to represent image, the axis 0 of the array is vertical, corresponding to Y axis of the image. So, to plot the points you need: plt.plot(points[:,1],points[:,0],'wo')...

python,matplotlib,nodes,shape,networkx

This is a pragmatic, rather than purely mathematical answer. I think you have two issues - one with layout, the other with your network. 1. Network You have too many edges in your network for it to represent the unit tesseract. Caveat I'm not an expert on the maths here...

Just an example to plot a 3D scatter plot and using an user defined colour map. import matplotlib.cm as cmx from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import matplotlib import numpy as np def scatter3d(x,y,z, cs, colorsMap='jet'): cm = plt.get_cmap(colorsMap) cNorm = matplotlib.colors.Normalize(vmin=min(cs), vmax=max(cs)) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm) fig...

python,arrays,matplotlib,scipy,scikit-learn

As @wflynny says above, you need to give np.meshgrid two 1D arrays. We can use X.shape to create your x and y arrays, like this: X=np.zeros((100,85)) # just to get the right shape here print X.shape # (100, 85) x=np.arange(X.shape[0]) y=np.arange(X.shape[1]) print x.shape # (100,) print y.shape # (85,) xx,yy=np.meshgrid(x,y,indexing='ij')...

python,pandas,matplotlib,datetimeoffset

As I mention in the comment, you potentially have two different problems You need to be able to plot a business times only timeseries without the long linear interpolations. You need an object that can do datetime arithmetic (in seconds) ignoring non-business times I've given a solution that will account...

You can almost get what you want by doing: g.plot(kind='bar') but it produces one plot per group (and doesn't name the plots after the groups so it's a bit useless IMO.) Here's something which looks rather beautiful, but does involve quite a lot of "manual" matplotlib work, which everyone wants...

python,for-loop,matplotlib,plot

You are trying to plot a line for each of your random points: the graph is blank because each single point isn't connected to any other. You could try building a list of the points and plotting that list as a line graph: xarr, yarr = [], [] for i...

python,excel,pandas,matplotlib,xlsxwriter

You can save the image to memory as a file object (not to disk) and then use that when inserting to Excel file: import matplotlib.pyplot as plt from cStringIO import StringIO imgdata = StringIO() fig, ax = plt.subplots() # Make your plot here referencing ax created before results.resid.hist(ax=ax) fig.savefig(imgdata) worksheet.insert_image(row,...

python,python-2.7,matplotlib,plot,histogram

As far as I know, matplotlib does not have this function built-in. However, it is easy enough to replicate import numpy as np heights,bins = np.histogram(data,bins=50) heights = heights/sum(heights) plt.bar(bins[:-1],heights,width=(max(bins) - min(bins))/len(bins), color="blue", alpha=0.5) Edit: Here is another approach from a similar question: weights = np.ones_like(data)/len(data) plt.hist(data, bins=50, weights=weights, color="blue",...

A couple of points: Numpy provides a very nice function for doing differences of array elements: diff Matplotlib uses plot_wireframe for creating a plot that you would want (also using Numpy's meshgrid) Now, combining these into what you may want would look something like this. from mpl_toolkits.mplot3d import Axes3D import...

python,numpy,matplotlib,heatmap,correlation

You can simply insert an extra singleton dimension in order to turn your (n,) 1D vector into a (1, n) 2D array, then use pcolor, imshow etc. as normal: import numpy as np from matplotlib import pyplot as plt # dummy correlation coefficients coeffs = np.random.randn(10, 10) row = coeffs[0]...

python,matplotlib,ipython,visualization,scientific-computing

A: This can be done at a cost of changed matplotlib Renderer Currently, this cannot be done for the IPython "inline" graphs, however, if you opt to change a Renderer part of the matplotlib framework, to another one, the limitation of a singleton call of the .show() method does not...

You need to specify when you vectorize the function that it should be using floats: vheaviside = np.vectorize(heaviside, [float]) otherwise, per the documentation: The output type is determined by evaluating the first element of the input which in this case is an integer. Alternatively, make sure heaviside always returns a...

python,pandas,matplotlib,histogram

This is a funny effect that appears to be present in pandas 0.16.0. Upgrading to 0.16.1 fixes it.

You can set clip_on=False in a Rectangle patch so that it can extend beyond the axis boundaries. import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np fig,ax=plt.subplots(2,1) x=np.linspace(0,np.pi*2,50) ax[0].plot(x,np.sin(x),'b-') ax[1].plot(x,np.sin(x),'b-') rect=mpatches.Rectangle([0.35,0.1], 0.1, 0.8, ec='k', fc='g', alpha=0.5, clip_on=False, transform=fig.transFigure) ax[1].add_patch(rect) fig.savefig('figure.png') Note: setting the rectangle on the first...

python,matplotlib,monkeypatching,seaborn

Seaborn does not change the behavior of matplotlib functions in the way you describe. Matplotlib exposes a number of options for customization that take effect by changing the default values of various plot parameters. When seaborn is imported, it runs some code that uses this functionality to change the global...