Menu
  • HOME
  • TAGS

how to avoid some function in the legend?

Tag: matplotlib

I need to include a line into a figure every time a button is clicked (I'm using pyqt4), this line has to be labeled and I also need to compare these lines with a constant function. Here is what I've tried:

labels = []
fig = plt.figure()
ax = fig.add_subplot(111, axisbg='white')
ax.hold(True)

def function(k):
   x = np.linspace(0, 2, 100)
   y = np.sin(k * np.pi * x) * np.exp(-5 * x)
   labels.append('k = {}'.format(k))
   ax.plot(x, y)
   # reference line
   plt.axhline(y=0.1, c='k', linestyle='--')
   plt.legend(labels)

for i in range(0,5):
   function(i)

plt.show()

The result: enter image description here

There is a simple way to skip the constant line marker in the legend frame?

Best How To :

Maybe I'm not following but it doesn't look like your reference line axhline(y=0.1, ...) is included in the legend.

I would set this separately, no reason to redraw it every time you plot a new line. Also try passing the label inside the plot function

fig = plt.figure()
ax = fig.add_subplot(111, axisbg='white')
ax.hold(True)
# reference line - only draw this once
plt.axhline(y=0.1, c='k', linestyle='--')

def function(k):
   x = np.linspace(0, 2, 100)
   y = np.sin(k * np.pi * x) * np.exp(-5 * x)
   ax.plot(x, y, linestyle='-', label='k = {}'.format(k)) # set label attribute for line

for i in range(0,5):
   function(i)

plt.legend() # you only need to call this once, it will generate based on the label assigned to line objects
plt.show()

Note: If you want to do this interactively (i.e. draw on a button press) then you'll have to call plt.legend() upfront and call plt.draw() after each new line is added, that way it'll update the legend.

standard form matplotlib — change e to \times 10

python,matplotlib

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...

How do I make each histogram bin show me the frequency of each action/event/item?

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 ...

Matplotlib: How to force integer tick labels?

python,matplotlib,plot

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...

Tricontour with triangle values

python,matplotlib

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...

show matplotlib colorbar instead of legend for multiple plots with gradually changing colors

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...

manipulating top and bottom margins in pyplot horizontal stacked bar chart (barh)

python,matplotlib,margins

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....

Python: matplotlib - probability mass function as histogram

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",...

backend not being reset by matplotlibrc.py

python,osx,matplotlib,backend

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...

Renaming the x-axis values in matplotlib

python-2.7,csv,matplotlib,graphing

You are looking for set_xticklabels

Matplotlib heatmap: Image rotated when heatmap plot over it

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') ...

Make a heatmap with a specified discrete color mapping with matplotlib in python

python,matplotlib

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...

Python (Matplotlib) - Tick marks on ternary plot

python,python-2.7,matplotlib

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]...

Making networkx plot where edges only display edited numeric value, not field name

python,matplotlib,networkx

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...

How to add shading through all subplot

python,matplotlib,plot

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...

Matplotlib: Plot the result of an SQL query

python,sql,matplotlib,plot

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 =...

Interactive pcolor in python

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.

Python plot Legend Key Format

python,matplotlib

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...

matplotlib mean interval plot

python,pandas,matplotlib,plot

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...

How to label and change the scale of Seaborn kdeplot's axes

python,matplotlib,seaborn

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...

Data Analysis and Scatter Plot different file and different column

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,...

How can I customize the offset in matplotlib

python-3.x,matplotlib

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...

Matplotlib Line2D unexpected behavior

python,matplotlib,plot

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)) ...

How do I install an external module from a wheel?

python,matplotlib,six

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....

matplotlib scatterplot: adding 4th dimension by the marker shape

python,matplotlib

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 =...

How to add legends and title to grouped histograms generated by Pandas

pandas,matplotlib

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...

IOError for savefig JPG in matplotlib

python,matplotlib,jpeg,canopy

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...

Read CSV and plot colored line graph

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...

Rebin data and update imshow plot

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:...

Plotting non-numeric x-axis away from the y-axis

python,matplotlib

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) ...

Creating a hexplot

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() ...

Read One Input File and plot multiple

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...

Need workaround to treat float values as tuples when updating “list” of float values

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...

How to index List/ numpy array in order to plot the data with matplotlib

python,numpy,matplotlib

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...

Matplotlib figure not updating on data change

python,matplotlib,pyqt4

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...

How to build custom pandas.tseries.offsets class?

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...

Plotting ordinal data with a marker in matplotlib

python,matplotlib

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...

Object-oriented access to fill_between shaded region in matplotlib

python,matplotlib,plot,fill

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...

How do I make a decaying oscilating function in python?

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)...

How to surround curves with annotation in matplotlib?

python,matplotlib

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:...

Turn off scientific notation and offset globally

python,matplotlib,plot

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...

How to add plot labels of different axes to the same legend in Python?

python,matplotlib,plot,axes

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...

Zipping ticklines does not allow to change their properties

python,matplotlib,python-3.4

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....

Why is the output of my function in binary?

python,numpy,matplotlib

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...

Matplotlib Legend Guide basic examples

python,matplotlib

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,...

Arrange line in front of bars in Matplotlib plot with double y axes

python,matplotlib,plot

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()...

Plot only one or few rows of a correlation matrix

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]...

How can I change the color of a grouped bar plot in Pandas?

python,pandas,matplotlib

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....

Matplotlib axis tick format changes after zoom in ipython figure window

python,matplotlib

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

Plotting two different arrays of different lengths

python,numpy,matplotlib,plot

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...

How to show minor tick labels on log-scale with Matplotlib

python,matplotlib

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() ...