How to scale figure down to a particular size in inches in matplotlib - plot

Suppose I prepare a PDF figure in matplotlib and let us say I have specified the original dimensions of the figure to be 10x10 inches. Would it be possible to produce essentially the same figure, but scaled down to 7x7in (so that all the fonts/point sizes, etc, would scale down appropriately)?
I do understand that I can open my 10x10 file in a vector graphics editor and perform the rescaling, but I was interested whether there is some simple switch that would do this directly from matplotlib.

Use set_size_inches, like so:
import matplotlib.pyplot as plt
fig=plt.figure()
ax=fig.add_subplot(111)
fig.set_size_inches([10,10])
ax.plot([1,3,2],[2,2,2],'ro-')
plt.savefig('10x10.png')
fig.set_size_inches([4,4])
plt.savefig('4x4.png')

Related

Jupiter notebook is printing words before plotting my images (not correct order)

In my code, I have it so that first images are plotted and then the user is asked to choose an image.
But when I run the cell, the user is first asked to choose an image and then the images are plotted. Not sure why.
Code in this picture:
Jupyter will render the plot after everthing else if it is running in 'inline' mode. I can't reproduce what you have exactly but take the following example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,10)
y = 5*x +2
plt.plot(x,y)
print('Text is here first even though the plot call comes last')
The output of this looks like:
Plot example without inline
So the plot is rendered last. Instead if we add '%matplotlib notebook' to the start. The plot will be rendered interactively and before the text. If you want to switch back just change it to '%matplotlib inline'. There are a number of other backend plotting options that are worth exploring.

different element sizes with matplotlib backend

I'm trying to accomplish a heatmap color bar to add extra info about the kdims in my heatmap. (Like the colSideColors option if you are familiar with R's heatmap.2 package.)
I can get a nice result with bokeh backend, but don't know how to get custom (different) element sizes when using matplotlib backend.
Can anyone tell me how to make the strip plot "shorter" (less "high") in the matplotlib backend example?
Setup
import pandas as pd
import numpy as np
import holoviews as hv
hv.extension('bokeh', 'matplotlib')
# dummy data
samples = ['sample{}'.format(x) for x in range(5)]
df = pd.DataFrame(np.random.rand(5, 5),columns=samples, index=samples).reset_index()
df = df.melt(id_vars='index', var_name='y').rename(columns={'index': 'x'})
# column means
df_strip = df.groupby('x').mean().reset_index()
df_strip['y'] = 'dummy'
# make plots
heatmap = hv.HeatMap(df, kdims=['x','y'])
strip = hv.HeatMap(df_strip, kdims=['x','y'])
Result with bokeh
%%output size=100 backend='bokeh'
(strip.options(xaxis=None, yaxis=None, height=50) +
heatmap.options(xrotation=90)).cols(1)
Result with matplotlib backend
%%output size=100 backend='matplotlib'
%%opts Layout [sublabel_format='' vspace=0.1]
(strip.options(xaxis=None, yaxis=None, aspect=1) +
heatmap.options(xrotation=90, aspect=1)).cols(1)
hv.__version__
'1.10.8'
The sizing unfortunately works very differently in the two backends, which means it can be somewhat difficult to get the same behavior. In this particular case you will want to set a larger aspect on the strip plot while also telling the Layout that it should weight the aspect when computing the size of the plots. Doing that looks something like this:
%%output size=100 backend='matplotlib'
%%opts Layout [sublabel_format='' vspace=0.1 aspect_weight=1]
(strip.options(xaxis=None, yaxis=None, aspect=5) +
heatmap.options(xrotation=90, aspect=1)).cols(1)

Drawing scatter graph using matlibplot.pyplot when points are duplicate

I want to generate a scatter graph using matlibplot.pyplot and a lot of points are duplicate. So when I simply draw a graph use pyplot.scatter method, many points are overdrawn on one dot. In order to consider the number of points on that position, I think I need to set a different point size, like a bigger circle if the spot contains more data points.
Can someone give me a pointer on how to do this? Thanks!
The easiest way to do this is to set a low alpha, and then when the points plot on top of each other they look darker.
import numpy as np
import matplotlib.pyplot as plt
data = [i for i in range(8) for j in range(np.random.randint(10))]
x, y = np.array(data), np.array(data)
plt.scatter(x, y, alpha=.1, s=400)
plt.show()
Of course, you can also change the size of the point or the color directly. To do this, you need to find the number of overlapping points and then set the size (using the s scatter plot parameter) or the color (using c) or both. (But setting alpha is easiest since it doesn't require explicitly counting the overlaps.)

Export graphics from R in vector format

I'd like to export graphics from R (for example, histograms and ROC curves) in vector format in order to make layout edits in a graphic design program like Intaglio. Is this possible?
pdf("myfile.pdf")
# graph goes here
dev.off()
Other devices (besides PDF) exist as well. (#Justin points out what is probably the most useful one in a comment).

How do I export a higher resolution image of a Mathematica Graph object?

How do I export a re-sized version of the output I get from a call to GraphPlot
(or TreePlot if they produce different output) to a jpg file?
Currently, I'm simply calling Export[file_name, G]
where G is the result from a call to something like GraphPlot.
I'm using Microsoft office picture manager to view the jpgs,
but re-scaling them there yields unsatisfactory results due to poor resolution
(the graph I'm trying to plot has strings as labels which can't be made out after rescaling this way). I would like to be able to choose the size/resolution of the rendered jpg.
As Simon already pointed out, don't use a raster-format for a vector-graphics. Instead, export you plot to e.g. a scalable vector graphics:
graph = GraphPlot[ExampleData[{"Matrix", "HB/can_292"}, "Matrix"]];
Export["graph.svg", graph]
The advantage is, that in such an image, you can still adjust and change lines, polygons and colors. And finally, you can export it to an image of arbitrary quality easily.
And remember, for Plots which contain lines, polygons, ... everything with sharp edges you should never use jpg. General speaking, this is a format for photographs only since its compression is made for reducing filesize in natural images. In those images you don't recognize the compression, in images with text, lines and polygons you certainly will notice the artefacts. Use png if possible. Take your browser and zoom into the above image.
You can set both image size and compression level of the exported file by doing something like
Export[file_name, G, ImageSize -> 1200, "CompressionLevel" -> 0]
The best way I find is to use ImageResolution property. It Increases the resolution of exported image but does not change the scale. Use it like this:
Export[ "image-file-name.png", image, ImageResolution -> 500 ]
Set the size of your graph before exporting it:
Graph[theGraph, ImageSize->2000]

Resources