Skip to main content

New answers tagged

0 votes

How can I stop a matplotlib table overlapping a graph?

You can use bbox option: import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize=(9, 5), dpi=300) ax = sns.barplot( x=range(1, 3), y=[15, 30], ) the_table = plt.table( ...
Hermann12's user avatar
  • 3,834
0 votes

How can I stop a matplotlib table overlapping a graph?

You can use pyplot.subplots to position barplot and table next to each other with space in between by adding each to an axe. import matplotlib.pyplot as plt import seaborn as sns fig, (ax_bar, ...
Bassem Ben Ghorbel's user avatar
0 votes

How can I stop a matplotlib table overlapping a graph?

The trick is to split your figure into two axes instead of drawing the table on top of the bar-axes;make_axes_locatable(ax) + append_axes("right", size="20%", pad=0.2) carves out a ...
Obaskly's user avatar
  • 779
1 vote

Linear regression prediction does not display properly

Instead of computing the lines using the coefficients, you can use the model's pred() method. It does the same thing of course; doing it manually like you did is a nice exercise. You also got the ...
Matt Hall's user avatar
  • 8,162
0 votes

How to reduce the space between bars in a Matplotlib chart?

You can adjust the gap precisely using width as follows: Here is an example of a very narrow gap: plt.bar(departments, students, width=0.95)
Charles Knell's user avatar
0 votes

Tikzplotlib module throws attribute error: module 'webcolors' has no attribute 'CSS3_HEX_TO_NAMES'

A bit late, but same answer to another question my apply: I faced similar issue along with some other problems due to the development of tikzplotlib being stalled. I forked the tikzplotlib and created ...
EdG's user avatar
  • 403
0 votes

AttributeError occurs with tikzplotlib when legend is plotted

A bit late, but same answer to another question my apply: I faced similar issue along with some other problems due to the development of tikzplotlib being stalled. I forked the tikzplotlib and created ...
EdG's user avatar
  • 403
0 votes

How to create a bar chart for this code using matplotlib

Your mistake is defining the win rate for each team as a list containing a single value. If you just modify those assignments (e.g., GenG_WR = 0.70; …; MR7_WR = 0.58) you can obtain a "correct&...
gboffi's user avatar
  • 25.2k
1 vote
Accepted

plt.contour() plots series of lines instead of a contour line

I think that your original data is a different size: maybe 3200 by 20, not 320 by 200. (You should check). The datafile does have 320 rows of 200 columns, but I suspect that is an artefact: maybe they ...
lastchance's user avatar
  • 7,174
0 votes

Can I make a multi-color line in matplotlib?

You can use matplotlib-multicolored-line package available on PyPI: import matplotlib.pyplot as plt import numpy as np from matplotlib_multicolored_line import colored_line from matplotlib.colors ...
mikm's user avatar
  • 166
0 votes

Matplotlib Colormap with two parameter

You can use a community package colormap-complex: from colormap_complex import colormap import matplotlib.pyplot as plt import matplotlib.patches as patches x = [1,1,2,2,3,3] y = [1,2,3,1,2,3] p1 = [...
mikm's user avatar
  • 166
1 vote

Is there any way to use bivariate colormaps in matplotlib?

You can use a community package colormap-complex: from colormap_complex import colormap import matplotlib.pyplot as plt import numpy as np lin = np.linspace(-1, 1, 100) x, y = np.meshgrid(lin, lin) z ...
mikm's user avatar
  • 166
0 votes

Can the Matplotlib PGF backend produce PDF files instead of PNG?

it's a bit old thread, but if someone still has this question I found a quick fix. In backend_pgf.py line 643, there is the following snipet: # save the images to png files path = ...
Paul's user avatar
  • 1
1 vote
Accepted

How to circumvent ImportError when invoking tikzplotlib?

I faced the same issue along with some other problems due to the development of tikzplotlib being stalled. I forked the tikzplotlib and created a new Python library out of it in which I fixed the most ...
EdG's user avatar
  • 403
3 votes
Accepted

Matplotlib vertical grid lines not match points

There are multiple solutions for it. I think using ax.set_xticks(df['Дата']) "to force the ticks to match your actual datetimes" might be better for you when the time of day matters, not ...
Subir Chowdhury's user avatar
1 vote
Accepted

Can't Align Histogram Bin Edges with Chart Even When Using Numpy histogram_bin_edges

The figure above was produced by the code below import matplotlib.pyplot as plt x = [74.030, 73.995, 73.988, 74.002, 73.992, 74.009, 73.995, 73.985, 74.008, 73.998, 73.994, 74.004, 73.983, ...
gboffi's user avatar
  • 25.2k
1 vote

Basemap plots in Matplotlib have cutoff map boundary lines

Okay, after more digging into the source code, I found a very crude solution that works. One option is to add the following line after the map plotting code that just turns off clipping for everything ...
Egor Lappo's user avatar
2 votes
Accepted

UserWarning: FigureCanvasAgg is non-interactive, and thus cannot be shown

I uses Linux Mint 22 based on Ubuntu 24.04. Code works for me with uv and Python 3.10 when I install PyQt6 but not with PyQt5 And it doesn't need line matplotlib.use('Qt5Agg') nor matplotlib.use('...
furas's user avatar
  • 144k
0 votes

Jupyter Notebook: automatically saves all images

If you want to extract images 🖼️ embedded inside a Jupyter Notebook (.ipynb file), you can easily do it with a Python script. Jupyter notebooks store embedded images as Base64-encoded strings under ...
Nihal Thakur's user avatar
1 vote
Accepted

Saving subplots in matplotlib as separate images

You have to call savefig inside the loop and use a unique figure name! f.savefig(f"cities{idx}.png")
raphael's user avatar
  • 3,023
0 votes

Realtime plot animation from JupyterLab

For some reason matplotlib was really really slow so I made my own widget import anywidget import traitlets import json import time from collections import defaultdict import numpy as np import uuid # ...
Rainb's user avatar
  • 2,475
1 vote

A water animation with velocity heatmap and changing surface level in python

I fixed it! When the vertical positions of velocity measurements aren't evenly spaced (like in this case), pcolormesh doesn't handle the curved shapes. So instead I treat each slice as a strip of ...
Darren Zammit's user avatar
0 votes
Accepted

I need to render a Plotter object on QWidget

I can't test it with your code but in documentation for Plot I found Plot.on(ax) (Plot.on(fig)) So maybe your code should use plot.on(ax) # plot.on(fig) or in one line with other functions plot = ( ...
furas's user avatar
  • 144k
1 vote

A water animation with velocity heatmap and changing surface level in python

If I replace this line of code in your second script, it works. timesteps, nx, ny = hraw.shape With random data, because we don’t know how you load the h raw and uraw. timesteps, nx, ny = 174, 200, ...
Hermann12's user avatar
  • 3,834
0 votes

How to remove duplicate matplotlib plot

You can try to add plt.ioff() shown as below to remove the duplicate plot. I found it is helpful when I encountered the same problem lately. Hope it helps. import matplotlib.pyplot as plt plt.ioff()
Pinkmei's user avatar
  • 69
4 votes
Accepted

How to plot 4*sin(2*x)/cos(2*x)**3 using Sympy?

SymPy's plotting module doesn't handle very well functions with poles. But SymPy Plotting Backends (which is a more advanced plotting module) is up for the task: from spb import plot plot(expr, (x, -...
Davide_sd's user avatar
  • 13.3k
0 votes

Matplotlib plots in pycharm suddenly don't show up in the pycharm plot window but as a popup window

Settings>Tools>Python Plots
vracker's user avatar
0 votes

How to add deep colored edges to the bars of a histogram with the same filled color of the bars?

The coloured edges in your PDF output appear because Matplotlib PDF backend (vector format) auto renders slight edge outlines when: alpha < 1.0 (transparency is used) histtype='barstacked' (which ...
Shinzou's user avatar
1 vote
Accepted

Why can I not get a continous curve when manually splitting a fitted curve into two parts?

The issue occurs in the following line of code: t_fit2_over = np.append(t_fit2_over, 900) This causes the data point corresponding to 900 to appear at the end of the second part instead of the ...
LittleNyima's user avatar
2 votes
Accepted

how to display metadata in scatter plot in matplotlib?

Matplotlib does not offer a built-in function in its core library to enable hover effects. For this functionality, you may consider using the mplcursor library. Kindly try running the code below ...
Subir Chowdhury's user avatar
0 votes

Ploting and viewing (x,y) points

Heavily inspired by https://matplotlib.org/stable/gallery/event_handling/coords_demo.htm import matplotlib.pyplot as plt import numpy as np from matplotlib.backend_bases import MouseButton t = np....
0 votes

Ploting and viewing (x,y) points

You can use Matplotlib with interactive cursor: import matplotlib.pyplot as plt import numpy as np from matplotlib.widgets import Cursor x = np.linspace(0, 10, 1000) y = np.sin(x) fig, ax = plt....
Szymon Roziewski's user avatar
2 votes
Accepted

How do I center vertical labels in a seaborn barplot?

Your text is correctly centered, however you only use letters that are above the baseline, which makes it look like it is not centered. See here for a description of matplotlib's alignment modes: So ...
mozway's user avatar
  • 264k
0 votes

How do I center vertical labels in a seaborn barplot?

import matplotlib.pyplot as plt import seaborn as sns percentages = [8.46950845e+00, 1.58712232e+01, 2.13963086e+01, 2.33865318e+01, 2.04539820e+01, 1.41358888e+01, 7.79622697e+00, 3.49245775e+00, 1....
Bhargav's user avatar
  • 4,301
0 votes

delete the redundant axis in colorbar

Add the below code after you add the colorbar axis, and turn off all ticks and labels on that axis: cax.tick_params( axis='x', which='both', bottom=False, top=False, ...
Omprakash S's user avatar
2 votes

For multi-index columns in pandas dataframe, how can I group index of a particular level value for visualization in Python?

You can create also create a fairly similar chart by creating a new Axes object per group of plots. Instead of relying on lines to create separation between groups, you can use the Common Region ...
Cameron Riddell's user avatar
3 votes
Accepted

For multi-index columns in pandas dataframe, how can I group index of a particular level value for visualization in Python?

I have been struggling a bit with finding a way to draw lines outside the plot area but found a creative solution in this previous thread: How to draw a line outside of an axis in matplotlib (in ...
Márton Horváth's user avatar
0 votes

Align twinx tick marks

Just adding to Floriaan's answer, I had noticed that the function did not work well for inputs round_to greater than 1, so I added a small checkup: def calculate_ticks(ax, ticks, round_to=0.1, center=...
Filip Maletic's user avatar
0 votes

Remove (sub)plot, but keep axis label in matplotlib

You could have a function like this def axis_off(ax, ticks=True, spines=True): """ removes frame around axis but leaves x,y labels there similar as ax.axis('off') which ...
pas-calc's user avatar
  • 145
2 votes
Accepted

produce nice barplots with python in PyCharm

Here is the code with changes: import matplotlib.pyplot as plt import seaborn as sns import pandas as pd l = [408, 321, 522, 942, 462, 564, 765, 747, 465, 957, 993, 1056, 690, 1554, 1209, 246, 462, ...
Omprakash S's user avatar
0 votes
Accepted

how to recover from error "Cannot mix incompatible Qt library (6.8.3) with this library (6.8.2)"

Thanks @furas for the hint: simply uninstalling qt6-main using `conda remove qt6-main` worked for me (conda installed/uninstalled a lot of other packages, unfortunately I didn't really paid attention ...
Andre's user avatar
  • 361
-2 votes

Matplotlib: Making axes fit shape limits

import matplotlib.pyplot as plt import matplotlib.patches as patches def draw_flowchart_and_save(): fig, ax = plt.subplots(figsize=(10, 18)) ax.set_xlim(0, 10) ax.set_ylim(0, 24) ax....
Christhoper Immanuel's user avatar
1 vote

How to plot data in straight line and in different line style depending on the data set

Starting from Gnuplot version 6.0.2, a new plot style called "hsteps" has been introduced. This style allows for easy creation of step-like line plots. The "hsteps" style is used ...
binzo's user avatar
  • 1,624
0 votes
Accepted

Aligning matplotlib subplots one with stacked bar plot and another with line plot using matplotlib in Python

I had to reset index of df1 and afterwards, it worked for me. fig, ax = plt.subplots() df2.plot(ax = ax, kind = "bar", stacked = True, color = color_map) df1....
hbstha123's user avatar
  • 1,730
1 vote

Matplotlib save cropped Image with patches, not figure

You can get rid of the margins by cropping the source image before using imshow and applying the patch. Since matplotlib still sets the figure size to the full image extents. Not sure if there is a ...
Raphael's user avatar
  • 1,185
0 votes

Get Line2D object from LineCollection

It is simpler to add label directly when you create lines (as @DavidG mentioned in comments) ax.vlines(..., label=...) or later use vlins.set_label(...) If you really need to use legend then you don'...
furas's user avatar
  • 144k
0 votes

Get Line2D object from LineCollection

I think a kind of "simple" approach is to create a dummy Line2D object with the desired properties (color, linestyle, label, ... you name it) that visually matches your vlines. You then add ...
jei's user avatar
  • 49
-1 votes

Plotting defined function

import numpy as np import matplotlib.pyplot as plt # Определяем функцию def f(x): return np.exp(7 * x - 14) # Генерируем значения x x = np.linspace(-3, 3, 400) y = f(x) # Создаем график plt....
user30238515's user avatar
0 votes

Centering a background gradient color map for a pd.DataFrame Styler object

An easier way is to use the gmap parameter of background_gradient(), feeding it the absolute values of the column of interest, since gmap is used to determine the actual color gradient for the column. ...
PJ_'s user avatar
  • 643
1 vote

How to visualize the PMF of a discrete distribution using a bar chart

The plt.hist() is designed to create histograms from a dataset of values, not to directly plot single probability values at specific x-coordinates. To visualize a discrete distribution's PMF (like ...
Lewis's user avatar
  • 1,353

Top 50 recent answers are included