logo
down
shadow

Is there a way to automatically make a "collage" of plots with matplotlib?


Is there a way to automatically make a "collage" of plots with matplotlib?

Content Index :

Is there a way to automatically make a "collage" of plots with matplotlib?
Tag : python , By : Govind Bhavan
Date : January 11 2021, 03:34 PM

hope this fix your issue You can use plt.subplots(). This allows you to add multiple plots to the same figure. You can configure the rows and columns to make a 2x2 grid or 4x1 or 1x4.
Another option, if you want more control of subplot size, is Matplotlib Gridspec.

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

matplotlib.pyplot.imshow: removing white space within plots when using attributes "sharex" and "sharey&qu


Tag : python , By : Dominique Vocat
Date : March 29 2020, 07:55 AM
it should still fix some issue As suggested here, adding:
ax.set_adjustable('box-forced')
ax2.set_adjustable('box-forced')

Preventing plot joining when values "wrap" in matplotlib plots


Tag : python , By : Keniwan
Date : March 29 2020, 07:55 AM
around this issue Here is a generator function that finds the contiguous regions of 'wrapped' data:
import numpy as np

def unlink_wrap(dat, lims=[-np.pi, np.pi], thresh = 0.95):
    """
    Iterate over contiguous regions of `dat` (i.e. where it does not
    jump from near one limit to the other).

    This function returns an iterator object that yields slice
    objects, which index the contiguous portions of `dat`.

    This function implicitly assumes that all points in `dat` fall
    within `lims`.

    """
    jump = np.nonzero(np.abs(np.diff(dat)) > ((lims[1] - lims[0]) * thresh))[0]
    lasti = 0
    for ind in jump:
        yield slice(lasti, ind + 1)
        lasti = ind + 1
    yield slice(lasti, len(dat))
x = np.arange(0, 100, .1)
y = x.copy()

lims = [0, 24]

x = (x % lims[1])

fig, ax = matplotlib.pyplot.subplots()

for slc in unlink_wrap(x, lims):
    ax.plot(x[slc], y[slc], 'b-', linewidth=2)

ax.plot(x, y, 'r-', zorder=-10)
ax.set_xlim(lims)

How to "Colormap/Heatmap" Multiple Line Plots in Python (matplotlib)


Tag : python , By : Ken
Date : March 29 2020, 07:55 AM
it helps some times Here's an example with some random length lines. The distance of the lines will have to be computed, and then normalised to the same range as a colormap. I picked 'hot', but you can pick any, the '_r' behind 'hot' reverses the colormap.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as mplcm
import matplotlib.colors as colors
import numpy as np
from random import randint

fig = plt.figure()
ax = Axes3D(fig)

num_lines = 50
lines, distances = [], []
for x in range(0, num_lines):
    xs = [0, randint(10, 150)]
    ys = [0, 5]
    zs = [0, randint(10,60)]
    lines.append([xs, ys, zs])

    distance = np.sqrt((xs[0]-xs[1])**2+(ys[0]-ys[1])**2+(zs[0]-zs[1])**2)  # calculate length of a line
    distances.append(distance)

distances_normalised = distances / (np.max(distances)/num_lines)  # normalise lengths of lines
cNorm = colors.Normalize(vmin=0, vmax=num_lines - 1)

cm = plt.get_cmap('hot_r')
scalarMap = mplcm.ScalarMappable(norm=cNorm, cmap=cm)

for dist, line in enumerate(lines):
    ax.plot(line[0], line[1], line[2], color=scalarMap.to_rgba(distances_normalised[dist]))

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

plt.show()

plotting a row of 3 plots using matplotlib and numpy but getting "IndexError: too many indices for array"


Tag : python , By : Elwillow
Date : March 29 2020, 07:55 AM
I wish did fix the issue. I am trying to plot a panel of 3 plots using matplotlib and the subplots() method. I have a numpy array of the mean values for the data and a second array for the standard error for the mean values. I tried to create a plot but keep getting an IndexError: too many indices for array. , If you issue the subplots command:
f, axarr = plt.subplots(nrows = 1, ncols=3)
In [7]: axarr.shape
Out[7]: (3,)
In [4]: axarr
Out[4]: 
array([<matplotlib.axes._subplots.AxesSubplot object at 0x7f0e299dead0>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7f0e107d3110>,
       <matplotlib.axes._subplots.AxesSubplot object at 0x7f0e1804d5d0>], dtype=object)

In [5]: axarr[0,0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-3e75475f2c86> in <module>()
----> 1 axarr[0,0]

IndexError: too many indices

How to add a loop to make multiple "two-group" scatter plots, and then automatically give same y-axis limits t


Tag : r , By : Jonathan
Date : December 23 2020, 07:30 PM
will be helpful for those in need Consider generalizing your plotting process in a method and call by (object-oriented wrapper to tapply) to iteratively run operation on each unique gene. For scales, calculate the min and max Reading between both groups beforehand:
User-Defined Function
proc_plot <- function(sub) {

  data_Group1 <- sub[sub$Groups == "Group1", ]
  data_Group2 <- sub[sub$Groups == "Group2", ]

  min_rdg <- min(data_Group1$Readings, data_Group2$Readings)
  max_rdg <- max(data_Group1$Readings, data_Group2$Readings)

  # Group1
  graph_Group1 <- ggplot(data_Group1, aes(x = TimePoint, y = Readings, group = Scale)) +
    labs(title="Group1", x="Time point", y="Readings") +
    scale_x_continuous(breaks = c(42.5, 47.5, 52.5, 57.5, 62.5, 67.5, 72.5),
                       labels = c("1", "2", "3", "4", "5", "6", "7")) +
    geom_line(aes(color = Scale), na.rm = TRUE) +
    geom_point(aes(color = Scale),size = 1.5, na.rm = TRUE) +
    scale_color_continuous(name = "Scale", breaks = c(5, 10, 25, 50, 75, 90)) +
    scale_y_continuous(limits = c(min_rdg, max_rdg)) +
    theme(legend.key.height = unit(3.5, "cm"))

  # Group2
  graph_Group2 <- ggplot(data_Group2, aes(x = TimePoint, y = Readings, group = Scale)) +
    labs(title="Group2", x="Time point", y="Readings") +
    scale_x_continuous(breaks = c(42.5, 47.5, 52.5, 57.5, 62.5, 67.5, 72.5),
                       labels = c("1", "2", "3", "4", "5", "6", "7")) +
    geom_line(aes(color = Scale), na.rm = TRUE) +
    geom_point(aes(color = Scale), size = 1.5, na.rm = TRUE) +
    scale_color_continuous(name = "Scale", breaks = c(5, 10, 25, 50, 75, 90)) +
    scale_y_continuous(limits = c(min_rdg, max_rdg)) +
    theme(legend.key.height = unit(3.5, "cm"))

  png (paste0("ScatterPlot_", sub$Biomarkers[[1]], ".png"), height=600, width=1111)
    output <- grid.arrange(graph_Group1, graph_Group2, nrow = 1, 
                           top=textGrob(sub$Biomarkers[[1]], gp=gpar(fontsize=20)))
  dev.off()

  return(output)
}
# BUILD PLOT LIST AND PNG FILES
plot_list <- by(data, data$Biomarkers, proc_plot)
dev.off()
grid.draw(plot_list$Gene1)

dev.off()
grid.draw(plot_list$Gene2)
Related Posts Related QUESTIONS :
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • the collatz func in automate boring stuff with python
  • How to find all possible combinations of parameters and funtions
  • about backpropagation deep neural network in tensorflow
  • Sort strings in pandas
  • How do access my flask app hosted in docker?
  • Replace the sentence include some text with Python regex
  • Counting the most common element in a 2D List in Python
  • logout a user from the system using a function in python
  • mp4 metadata not found but exists
  • Django: QuerySet with ExpressionWrapper
  • Pandas string search in list of dicts
  • Decryption from RSA encrypted string from sqlite is not the same
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com