ppinard / matplotlib-scalebar Goto Github PK
View Code? Open in Web Editor NEWProvides a new artist for matplotlib to display a scale bar, aka micron bar.
License: BSD 2-Clause "Simplified" License
Provides a new artist for matplotlib to display a scale bar, aka micron bar.
License: BSD 2-Clause "Simplified" License
Is there a way to fine adjust the scalebar position? I need to place the scalebar at the lower right of a image, but there is a label that also needs to be there and I´d like to raise the scalebar a few pixels, so both will be on the lower right but not overlapping each other.
Less of an issue, more of an announcement for people using this library for cartographic visualization:
I just developed a package (matplotlib-map-utils) for adding print-ready north arrows to matplotlib plots. It includes a bevy of customization options, as well as the ability to automatically calculate the direction to "true north" if provided a CRS.
It is heavily inspired by this package, and thought it might be of interest to those using matplotlib-scalebar to create scale bars for maps specifically.
It seems development has also slowed on this package. I am hopeful that v2
of my package will include functionality for creating cartographic scale bars (like what is available in ArcGIS and QGIS) - if this is something you would use, feel free to drop a comment! I am not currently committing to any timeline for releasing v2
, but if enough interest is expressed, I am happy to prioritize it over my other personal projects.
Most of all though, thank you to the developers of this package, as I was able to puzzle out a fair bit of functionality I re-used in my package thanks to the source code shared here!
Hi,
Sometimes I don't really know the unit of the picture and the axis is turned off for aesthetic reason. It would be nice to have a scale bar just for showing how many pixels a certain length of the picture spanned.
Hey, it looks like the latex representation of micro does not work, because the _Dimension.calculate_preferred will overwrite the "µm" unit with "um".
I fixed it by monkey patching this method for now, but I a proper solution would be better :D
Dear all,
first of all, thank you very much for this, scalebars are kinda mandatory in research and having this in python is really nice.
I am having some issues when using ScaleBar. The bar does not correspond to the actual size it would have; could you help me with that?
I'm using this code:
from matplotlib_scalebar.scalebar import ScaleBar
from skimage.io import imread
len_px = 0.00048223304582578836
image = imread('dur_grain1apatite01.tif', as_grey=True)
fig, ax = plt.subplots(figsize=(15, 10))
ax.imshow(testimg_apatite)
scalebar = ScaleBar(dx=len_px,
units='mm',
fixed_value=25,
fixed_units='um',
location=4,
box_alpha=0,
font_properties={'family' : 'monospace',
'weight' : 'semibold',
'size' : 20})
fig.gca().add_artist(scalebar)
plt.show()
This is the example image.
Thank you very much for your support.
Can you change the definition of the symbol of greek mu (as in the micrometer) such that it uses the font defined in the script in which matplotlib-scalebar is being imported? Using the \mathregular command should be enough. e.g. mu = '\mathregular{ \mu }'
Hi,
I am trying to add a scalebar using the sample scripts in geemap. But I am getting wrong results. The pixel size of the satellite imagery is 10m.The output is coming as
Which is wrong,
The script which I used is,
oi =m.draw_last_feature
geom = roi.geometry()
coords = geom.coordinates().getInfo()
zoom_region = [coords[0][0][0], coords[0][0][1], coords[0][2][0], coords[0][2][1]]
fig = plt.figure(figsize=(10,20))
vis = {
"bands":["VV"],
"min":-25,
"max":0,
"palette":['aqua', 'black']
}
# use cartoee to get a map
ax = cartoee.get_map(Sentinel_1,vis_params=vis,region=zoom_region)
# add gridlines to the map at a specified interval
cartoee.add_gridlines(ax,interval=[0.005,0.005],linestyle=":")
ax.set_title(
label = 'Sentinel-1, October 5,2020 ',
fontsize = 15
)
scalebar = ScaleBar(10) # 1 pixel = 0.2 meter
ax.add_artist(scalebar)
plt.show()
Kindly suggest ways to fix it.
Thank you.
Would it be possible to add an arrow head to the scalebar? Then it could be used with quiver plots.
It would be great to make a a new patch release!
In particular, the updates from #53 (e.g. switch from setup.py
to pyproject.toml
) are not released yet. As a consequence, build of the arch package fails on python 3.12:
https://aur.archlinux.org/packages/python-matplotlib-scalebar#comment-970767
Hi @ppinard!
I've just written an example gallery for the matplotlib-scalebar package:
https://kolibril13.github.io/plywood-gallery-matplotlib-scalebar/
One can click on one image and the corresponding code will be displayed.
Feedback is welcome!
What do you think about mentioning this gallery in the readme?
Hey,
nice package!
One thing came to my mind using it: The \mu for micrometer is of italic type which is not correct in my opinion.
You could change:
latexrepr = '$\\mu$m'
to
latexrepr = '$\\mathrm{\\mu}$m'
in dimensions.py, line 88.
Best,
SJF
I am in the USA, and few people here are good at meters / kilometers, so I do have to use the Scalebar's imperial-length dimension when creating maps in geopandas. Unfortunately, the scale won't stay in miles if you are zoomed in such that the extent of the map is now at a sub-mile level. So at that point the scalebar shows furlongs or chains instead of fractions of a mile, and furlongs and chains are not something anyone here is familiar with.
It would be very nice to be able to display in fractions of a mile (to the tenth's place, unless it is 0.25 or 0.75) instead of in furlongs or chains. It also works to display in feet (10ft, 30ft, 50ft, 100ft, 200ft, 500ft, 1000ft, 2000ft). I really hope this can be a feature that is added to this otherwise wonderful scalebar.
I've attached this map as an example of how the scalebar displays chains (ch) or furlongs (fur) instead of miles or feet:
Every time I import ScaleBar as here,
%matplotlib inline import matplotlib.pyplot as plt from matplotlib_scalebar.scalebar import ScaleBar
I get the following warning
C:\Anaconda2\lib\site-packages\matplotlib_init.py:1357: UserWarning: This call to matplotlib.use() has no effect
because the backend has already been chosen;
matplotlib.use() must be called before pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.
warnings.warn(use_error_msg)
Can you please check what is going on here. I am on Windows 10 with Anaconda 32 bit Python 2.7
First, thanks for the great package!
I just ran into a use case that I hadn't before, and I'm wondering if there's a way to deal with it. I'm trying to get the scalebar value from a scalebar object created with length_fraction (and thus an automatically chosen value) so that I can use it in another place. Eg, in the below plot, I want to get the value of 25
or 25 m
out so that I can use it. Is there a way to do this?
import matplotlib_scalebar.scalebar as scalebar
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(np.arange(100))
scale_bar = mpu.add_traj_scalebar(ax, dx=1, length_fraction=0.3, location="lower right")
# How can I do this?
# scale_bar_value = scale_bar.
The font_properties argument in the ScaleBar constructor behaves different from the doc
from matplotlib.font_manager import FontProperties
gca().add_artist(ScaleBar(.1, font_properties=FontProperties(size = 12)))
results in an error ("TypeError: 'FontProperties' object is not iterable").
I assume the reason is in the line
self.font_properties = FontProperties(font_properties)
but should be
self.font_properties = font_properties
(after changing that, everything works fine)
PS:
Thanks for the package!
Hi Philippe,
there is a print() statement in line 322 of scalebar.py which leads to some uncalled-for output e.g. in jupyter notebooks etc. when using the scalebar. I guess this is left over from debugging/testing and could be removed...
Best regards,
Aimo.
It is sometimes useful to have a scalebar without scale or label, just the line. For example, if you already mention the scale in the figure caption. I have not found a way to hide the scale. Is it possible to implement it?
Thanks.
Hi it seems like reloading matplotlib using imp
as you do on line 81 in scalebar.py
causes some issues with custom settings.
For example:
from matplotlib_scalebar.scalebar import ScaleBar
from matplotlib_scalebar.dimension import _Dimension
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams.update({'font.family': 'serif'})
As you can see the fonts are sans-serif and not serif.
Doing the same without importing matplotlib_scalebar, will lead to the expected result:
# from matplotlib_scalebar.scalebar import ScaleBar
# from matplotlib_scalebar.dimension import _Dimension
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams.update({'font.family': 'serif'})
By playing around with a local install of your package I could verify, that reloading matplotlib (line 81) causes this issue.
imp.reload(sys.modules['matplotlib'])
Removing that line resolves the issue and does not seem to change anything else. (all test still work and all other things I tested, too)
Could you explain what the original intention of this line was?
Best regards,
Arne
(PS: awesome package otherwise! Saved me a lot of time!)
I noticed that the scalebar incorrectly handles the prefix for reciprocal units, I noticed this when I was trying to measure distances in a Fourrier transform of an image. My original image has a pixel size of 0.007 nm/pixel, but everything is stored in meters, so 7e-12 m. The scalebar has no problem interpreting this value and puts a scalebar in nm on the image.
To calculate the scale of my Fourrier transform, I take the meters value and convert. My image is 4096x4096 pixels so the scale in the FFT is 1/(7e-12 * 4096)=3.4e7 m^-1/pixel. This is equivalent to 0.034 nm^-1/pixel. When I pass the scale in nm^-1 to the scalebar, it uses the correct nm^-1 units. However, when I pass the scale in m^-1, the scalebar uses Gm^-1.
Dear all,
I have recently tried the matplotlib-scalebar module over some geopandas geodataframe plot. I noticed that the the given module does not well support the plot. This is due to the "dx" argument. Since the geopandas plot does not have a size of pixel, the "dx" setting is akward, and prone to errors.
Sincerely yours,
Philipe Leal
Hi,
I was wondering is it possible to add two scale bars: one for the x-axis and another one for the y-axis. The x-axis of my plot is in milliseconds and the y-axis in pico ampers.
I have generated the following plot but, I want the unit of the plot being "ms" which the program does not allow. I also want to add another scalebar for the y-axis, so that I can hide the axis.
scalebar = ScaleBar(1, label='ms', location='lower right')
plt.gca().add_artist(scalebar)
This package is exactly what I've been looking for years, for use with geopandas. Thanks you!
Would it be possible to add the bbox_to_anchor, in addition to location? The documentation looks like it works but I got the following error: TypeError: ScaleBar.init() got an unexpected keyword argument 'bbox_to_anchor'.
It would be very useful for astronomers to have a scale bar showing angular scales such as degree (°), arcmin (') and arcsec ('').
For example, this can be done by adding the so-called pixel scale
in the units of arc seconds per pixel (or even more available units) as an input. For example pixel scale = 0.2
implies that each pixel spans 0.2 arcsec. Here is the best I could do with the current version of matplotlib-scalebar
.
Dear developers,
I would like to thank you for the amazing package you have developed.
I was wondering if it would be possible to enhance it in order to accomodate multiple patches within a same scalebar. Something like Quantum-GIS does (see example below).
I created a discussion in StackOverflow regarding the use of the matplotlib.offset VPacker and HPacker on this regard (in here).
Sincerely,
I'm trying to plot just a scalebar without any associated text that says what's the length and unit of scale bar. What's the best way to do this?
Hi, Is it currently possible to place the text above the scale bar? The README mentions setting the scalebar.label_top rcParam but there is no reference to this in the code and it doesn't seem to do anything when I try it. I'm also unclear on what the scale_loc and label_loc parameters are for; I don't see any effect from those.
-- edit --
Just after creating this question, I discovered that I can enter a negative value for the sep parameter and this places the text above the scalebar. I don't suppose this is intentional but I'll do this as a workaround for the moment.
See discussion in #19
This looks very useful! Could you add a blurb like those at
https://matplotlib.org/thirdpartypackages/index.html (source is at
https://github.com/matplotlib/matplotlib/blob/master/doc/thirdpartypackages/index.rst) ?
Hi!
I want to save my plot with the ScaleBar, here is my code:
fig, ax = plt.subplots()
ax.axis("off")
ax.imshow(my_slice3, cmap="gray")
scalebar = ScaleBar(650, "nm", length_fraction=0.25, location= "lower right")
ax.add_artist(scalebar)
plt.savefig('foo.png')
When I save the image, the resolution is not anymore the resolution of the original image.
At Stack Overflow I found the hint, that one can use imsave
, but that is not working with the Scalebar.
https://stackoverflow.com/questions/31544130/saving-an-imshow-like-image-while-preserving-resolution
I know that I can increase the resolution e.g. with
plt.rcParams['figure.dpi'] = 300
.
But that is not leading to the exact pixel-by-pixel image.
Any idea how to solve this?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.