# Questions tagged [matplotlib]

12730 questions

1

votes

1

answer

215

Views

### Matplotlib x-axis overcrowded label rendering

I'm trying to simply plot a numpy array but I'm having troubles, especially with getting the number of ticks and labels right on the x-axis.
I'm dealing with an array named percents that looks like this:
percents:
-74 0.000041
-61 0.000041
-60 0.000041
-59 0.000041
-57 0.000041
...
71...

1

votes

1

answer

2.1k

Views

### A tornado chart and p10-p90 in python (matplotlib)

I need to plot the following two things using the Python (matplotlib):
A tornado chart (kinda summarizing the sensitivity analysis)
And a comparison of mean p10 and p90 values for a list of variety products.
I have never done this before and was trying to use Python (matplotlib). So far no success....

1

votes

1

answer

32

Views

### Graph Keeps Growing, Even After Clearing It

I am trying to graph two different graphs using this Python program:
K_5=nx.complete_graph(10)
print(K_5.number_of_nodes(), K_5.number_of_edges())
nx.draw(K_5)
plt.savefig('test1.png')
K_5.clear()
G = nx.Graph()
G.add_node(8)
nx.draw(G)
plt.savefig('test2.png')
print(G.number_of_nodes(), G.number_of...

1

votes

1

answer

740

Views

### Transition line in heat map - python

I have problem that I can't seem to work around. I have a grid of values that I have interpolated using scipys griddata. The values have been visualized as a heat map with values in [0,1]. Now I would like to plot a transition line for values 1/2.
Is this possible? My first idea was to extract the c...

2

votes

1

answer

15

Views

### Can't change width when annotating bar

I'm creating a stacked horizontal bar graph with 3 segments using the code below:
import matplotlib.pyplot as plt
import numpy as np
def create_stacked_hbar(data):
fig, ax = plt.subplots(figsize=(10, 10))
ylabels = list(data.keys())
labels = ['a', 'b', 'c', 'd', 'e', 'f']
c = []
v = []
f...

2

votes

1

answer

22

Views

### Two tick labels overlap in the plot with symlog scale

I have made a plot with symlog on x-axis, and intend to make the linear region short enough (linscalex = 0.2). Please see my graph. However, the first tick label (1e-2) of the log region overlaps with the origin (0). Is there anyway to remove the tick label 1e-2?
Here is my code
plt.xscale('symlog',...

1

votes

1

answer

1.1k

Views

### Fails to install matplotlib using pip3 on FreeBSD

I always get the following error message
[email protected]:~/anythingCollector % sudo pip3 install matplotlib
Collecting matplotlib
Using cached matplotlib-1.5.0.tar.gz
Complete output from command python setup.py egg_info:
IMPORTANT WARNING:
pkg-config is not installed.
matplotlib may not be able to...

1

votes

2

answer

359

Views

### Specifying values for my x-axis using the matplotlib.pyplot?

I am not able to specify values for my x-axis , using the matplotlib.pyplot.
In some images the chart.xticks(years) solves the problem , but it seems that when the set of x-axis values is too small , it uses default values like [0,1,2,...,N].
A case that works:
A case that does not...

0

votes

0

answer

3

Views

### tight_layout with more than 4 twinx axes has extra padding

I am running a script to plot a set of up to 6 curves sharing a common timeline. I am using twinx() up to 5 times and getting up to 4 detached axes on the right side of the plot. The script (shown below) is derived from this example. However, the recipe for drawing the extra axes shown in that examp...

1

votes

1

answer

125

Views

### What happened to the parameters when the function was called?

I am looking at how to format axis tick marks in matplotlib
http://matplotlib.org/examples/pylab_examples/custom_ticker1.html
The link shows the following pieces of code
def millions(x, pos):
'The two args are the value and tick position'
return '$%1.1fM' % (x*1e-6)
I am having trouble with understa...

1

votes

1

answer

697

Views

### How to delete and resize matplotlib annotations?

I am using the basic axis.annotate(str(i)) function to show values along the points of my graph. The problem is quite quickly they get to bunched together. So I have two questions: How can I remove an annotation? And how can I make one smaller (font size)?
Here is the reference to the annotation met...

1

votes

2

answer

467

Views

### Draw ellipse in matplotlib given the focii

The equation of an ellipse is:
sqrt((x-a1)**2 + (y-b1)**2) + np.sqrt((x-a2)**2 + (y-b2)**2) = c
The focii are (a1, b1) and (a2, b2). c is also known. How do I draw this in python using matplotlib?
Thanks for your help.

1

votes

2

answer

527

Views

### matplotlib surface plot for (x-y)^2

Can anyone help me with plotting a 3D surface plot for the equation f(x,y) = (x-y)^2
The Z axis should represent the function f(x,y)
I have the below function:
def fnc(X):
return (X[0] - X[1]) ** 2
Here X is a numpy array with first parameter as X and the second as Y.
I specifically need it to be th...

1

votes

2

answer

1k

Views

### Error in Python Code when plotting in Seaborn

I am trying to plot distribution graph in python using seaborn . But I am getting error which I am not able to solve given below.
Code:
sns.distplot(df['nn'])
error:
cannot convert float NaN to integer
Is there any efficient way to solve this by plotting histogram and the distribution.

0

votes

0

answer

12

Views

### How to make a multiwaveplot in Python

I want to plot a multichannel signal in a way similar to the picture below:
enter image description here
Does someone know if there is a function within matplotlib or any other Python library that makes such plots? I have tried with the joypy library, but the results were not that good.
Thanks in ad...

1

votes

2

answer

25

Views

### Matplotlib histogram does not show details of distribution

I have some data and I would like to look at its distribution. But I don't know why when I use this code, the histogram does not really show what is going on within the data and it shows a very general picture. I want to have a more granular histogram.
data['feature'].plot(kind='hist')
And here is w...

0

votes

0

answer

27

Views

### Plot the difference between two lists of values in matplotlib

I have two datetime based lists. I want to plot the difference between their values.
The problem is, the lists are of different lengths / resolutions.
For example:
list 1 is a list of readings taken every minute throughout the day.
list 2 is a list of readings taken randomly throughout the day.
I c...

1

votes

1

answer

70

Views

### plotly: how to make a standalone plot in a window?

Is there any way to use plotly just like matplotlib, that is, making the plot appear in a pop up window? Eg, is there an simple equivalent of
plt.plot([1,2,3], [2, 3, 2.5])
plt.show()
I've tried various functions, but all of them seem to either create an html file or an image file.

1

votes

2

answer

50

Views

### How to merge different time-series plot into a 2D in Python

I have three different time-series data of the following format where the first column is timestamp and the second column is the value.
0.086206438,10
0.086425551,12
0.089227066,20
0.089262508,24
0.089744425,30
0.090036815,40
0.090054172,28
0.090377569,28
0.090514071,28
0.090762872,28
0.090912691,27...

1

votes

2

answer

53

Views

### Why won't my Python async / await actually write matplotlib files?

My code is:
import os
import h5py
import asyncio
import numpy as np
import matplotlib.pyplot as plt
from dotenv import load_dotenv
load_dotenv()
data_path = os.environ['DATA_PATH']
output_data_path = os.environ['OUTPUT_DATA_PATH']
patient_files = os.listdir(data_path)
async def save_file(filename, i...

0

votes

0

answer

4

Views

### Select part of row values

I have a dataset like this:
S.No Param 1st 2nd 3rd 4th....15th
1 a 65 45 86 52 ....
2 b 62 666 8 785....
I want to plot freq for each param and the columns after that till 15th
I have taken the set of columns and extracted them from S.No and Param. Now the dataset...

1

votes

1

answer

1.1k

Views

### How to detect that an axis belong to a window that has been closed in matplotlib

In matplotlib, I keep a reference on an axis. I want to open a new figure if the window that contain the axis have been closed. The idea is to keep adding plots on the figure, until it is closed, then I open a new figure.
Note that the creation of new plots is triggered by an event in another figur...

1

votes

2

answer

28

Views

### How do I plot y=x+i for i = [1:16]?

I should be getting 16 individual lines, but the endpoint of the first line back tracks and meets the starting point of the next line. How do I fix this?
a = []
b = []
x = 0
for i in range(1,17):
for x in range(0,5):
y=x+i
a.append(x)
b.append(y)
fig= plt.figure()
axes=fig.add_subplot(111)
pylab.pl...

0

votes

0

answer

2

Views

### Matplotlib get Axes artist object for ArtistAnimation?

I am trying to make an animation using ArtistAnimation like this:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
ims = []
for i in range(60):
x = np.linspace(0,i,1000)
y = np.sin(x)
im = ax.plot(x,y, color='black')
ims.append(im)...

0

votes

0

answer

6

Views

### Which parts of my dataframe are being plotted?

The goal is to plot the data frame I'm working with on a single chart, with a line for each value of init_population where the y-axis is count and x-axis is tick_number
I've figured out how to use groupby() and plot() together to make this
As you can see, all the lines are there nicely, but I'm...

0

votes

0

answer

15

Views

### How to create a drag and drop timeline in matplotlib

I have created a timeline to map sound files from a table, however I am struggling to find resources that use drag and drop in matplotlib. I want to allow users to move the position of the individual bars horizontally.
So far I have looked at Event handling in matplotlib, but I am not sure how to ge...

0

votes

0

answer

8

Views

### Folium - choropleth does not return any choropleth

No choropleth map is returned ...
"Fylker_with_count_rest" in the codes, my data set, is just the download of https://www.eriksmistad.no/upload/fylker.json
except that after downloading, I added a column (Nummer_Restauranter) of integers into it.
What I want to do is to make a choropleth map which s...

1

votes

1

answer

480

Views

### Python: make consistent 3D plot out of point values

In a 2D plane, I have a set of nxn points defined by their (x,y) coordinates. For each point, there exists a certain quantity that I want to plot as a 3D surface. How can I do it in such a way that each point is assigned the relevant value in the plot? I ask because I am getting a messed up plot.
I'...

1

votes

1

answer

940

Views

### MatplotLib get all annotation by axes

i'm doing a project with Python and Tkinter. I can plot an array of data and i also implemented a function to add annotation on plot when i click with the mouse, but now i need a list of all annotation that i added. Is there any way to have that?
This is my function to add annotation:
def onclick(s...

1

votes

1

answer

382

Views

### Python StatsModels Time Series Decomposition Duplicate Plot

I am using a mixture of Pandas and StatsModels to plot a time series decomposition. I followed this answer but when I call plot() it seems to be plotting a duplicate.
My DataFrame looks like
My index looks like
but when I plot the decomposition I get this
Strangely, if I plot only an element of the...

1

votes

2

answer

584

Views

### Matplotlib stacked histogram using `scatter_matrix` on pandas dataframe

Currently I have the following code
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import scatter_matrix
df= pd.read_csv(file, sep=',')
colors = list('r' if i==1 else 'b' for i in df['class']) # class is either 1 or 0
plt.figure()
scatter_matrix(df, color=colors )
plt.show(...

1

votes

1

answer

2.4k

Views

### Jupyter: How to update plot on button click (ipywidgets)

I am using Jupyter and trying to make my plots interactive.
So I have a plot. I have a ipywidgets button.
On button click I need to update plot, like interact do with sliders.
But I can't.
It works only if matplotlib uses 'notebook' backend, but it looks terrible. At same time interact works with an...

0

votes

0

answer

5

Views

### Python TypeError: float() argument must be a string or a number, not 'SingleBlockManager'

I would appreciate any input. I was previously able to obtain image using this code but going back through my work it is now giving me this error. Any ideas how I can fix this?Perhaps this is due to upgrading matplotlib recently?
Code I am using
import pandas as pd
import numpy as np
np.random.seed(...

1

votes

2

answer

391

Views

### matlibplot: How to add space between some subplots

How can I adjust the whitespace between some subplots? In the example below, let's say I want to eliminate all whitespace between the 1st and 2nd subplots as well as between the 3rd and 4th and increase the space between the 2nd and 3rd?
import matplotlib.pyplot as plt
import numpy as np
# Simple d...

1

votes

1

answer

51

Views

### matplotlib histogram plot 'density' argument not working

I try running the following code
import numpy as np
import matplotlib.pyplot as plt
x = np.random.randn(1000)
plt.hist(x, bins=50, density=True)
plt.show()
And I get the following error message:
AttributeError: Unknown property density
What's wrong?

0

votes

0

answer

13

Views

### Invalid dimension for image data in plt.imshow()

I am using mnist dataset for training a capsule network in keras background.
After training, I want to display an image from mnist dataset. For loading images, mnist.load_data() is used. The data is stored as (x_train, y_train),(x_test, y_test).
Now, for visualizing image, my code is as follows:
img...

-3

votes

1

answer

28

Views

### Python put add sentence as image in matplotlib

I have a text:
"Hello world"
and a heat map as a 2d-array.
I want to draw the text as a graph in order to put the heatmap on top of it.
So, my question is how to convert the string "Hello world" to an image in order to plot it?
For example, I want to create this .png:

0

votes

0

answer

8

Views

### How can I add a legend to a Matplotlib pie chart without using proxy artists?

I'm trying to reduce the size of a pie chart I've made using matplotlib by incorporating a legend. I think the two biggest problems are that I have 18 pie wedges, and using a sample code I incorporated a color map in a funky numpy array I don't quite understand.
I've done some digging and I think I...

0

votes

0

answer

16

Views

### Animated plot for bar graph and line graph using python subplot

I was able to plot animated graphs using advice from the link below.
matplotlib animation multiple datasets
And my code is here.
tt = time_hr.values[:,0]
yy1 =data1.values[:,0]
yy2 =data2.values[:,0]
fig, ax = plt.subplots()
line1, = ax.plot(tt, yy1, color='k')
line2, = ax.plot(tt, yy2, color='r'...

0

votes

0

answer

6

Views

### Blank Seaborn Chart in PyQT

I'm trying to embed a Seaborn chart in PyQT5. The current result is a blank chart. I've verified that I'm passing a legitimate df to the create_graph method and I've read the Seaborn documentation for a lineplot here.
class PlotCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4,...