Graphics Plotting ggplot - ggplot2

I'm trying to make a grid in ggplot to plot 4 graphs, as if it were a basic pair (mfrow = c (2,2)). However, I can not execute the code. I have already tried with gridExtra and cowplot with the functions plot_grid, grid.arrange, ggplot2.multiplot and also tried with the multiplot function. The error that appears is as follows:
Error: Aesthetics must be either length 1 or the same as the data (8598): alpha, x, y, group

gridExtra::grid.arrange(ggplot(),ggplot(),ggplot(),ggplot(), nrow=2)
produces
you may want to debug your code for each individual plot first.

Related

Matplotlib heatmap is not sized correctly

I am trying to plot one dependent variable vs two independent variables using matplotlibs heatmap feature, however, I cannot get the image to display correctly. Code and image below.
plt.xticks(np.arange(0, .015, .0015))
plt.yticks(np.arange(-.0005, .0005, .00005))
plt.scatter(Dataset.Gate, Dataset.Bias, c = Dataset.Current)

Difference between matplotlib.countourf and matlab.contourf() - odd sharp edges in matplotlib

I am a recent migrant from Matlab to Python and have recently worked with Numpy and Matplotlib. I recoded one of my scripts from Matlab, which employs Matlab's contourf-function, into Python using matplotlib's corresponding contourf-function. I managed to replicate the output in Python, apart that the contourf-plots are not exacly the same, for a reason that is unknown to me. As I run the contourf-function in matplotlib, I get this otherwise nice figure but it has these sharp edges on the contour-levels on top and bottom, which should not be there (see Figure 1 below, matplotlib-output). Now, when I export the arrays I used in Python to Matlab (i.e. the exactly same data set that was used to generate the matplotlib-contourf-plot) and use Matlab's contourf-function, I get a slightly different output, without those sharp contour-level edges (see Figure 2 below, Matlab-output). I used the same number of levels in both figures. In figure 3 I have made a scatterplot of the same data, which shows that there are no such sharp edges in the data as shown in the contourf-plot (I added contour-lines just for reference). Example dataset can be downloaded through Dropbox-link given below. The data set contains three txt-files: X, Y, Z. Each of them are an 500x500 arrays, which can be directly used with contourf(), i.e. plt.contourf(X,Y,Z,...). The code that used was
plt.contourf(X,Y,Z,10, cmap=plt.cm.jet)
plt.contour(X,Y,Z,10,colors='black', linewidths=0.5)
plt.axis('equal')
plt.axis('off')
Does anyone have an idea why this happens? I would appreciate any insight on this!
Cheers,
Jussi
Below are the details of my setup:
Python 3.7.0
IPython 6.5.0
matplotlib 2.2.3
Matplotlib output
Matlab output
Matplotlib-scatter
Link to data set
The confusing thing about the matlab plot is that its colorbar shows much more levels than there are actually in the plot. Hence you don't see the actual intervals that are contoured.
You would achieve the same result in matplotlib by choosing 12 instead of 11 levels.
import numpy as np
import matplotlib.pyplot as plt
X, Y, Z = [np.loadtxt("data/roundcontourdata/{}.txt".format(i)) for i in list("XYZ")]
levels = np.linspace(Z.min(), Z.max(), 12)
cntr = plt.contourf(X,Y,Z,levels, cmap=plt.cm.jet)
plt.contour(X,Y,Z,levels,colors='black', linewidths=0.5)
plt.colorbar(cntr)
plt.axis('equal')
plt.axis('off')
plt.show()
So in conclusion, both plots are correct and show the same data. Just the levels being automatically chosen are different. This can be circumvented by choosing custom levels depending on the desired visual appearance.

Generating subplots of heatmaps in Julia-lang

I am trying to produce a figure/plot with more than a single heatmap (matrix with color shading according to the cell value). At the moment using Plots;
pyplot() and heatmap(mat) is enough to produce a heatmap.
It is not clear to me how to produce a single figure with more though. After looking at this page example subplots for how to use the layout, and then the example histogram, I cannot seem to produce working examples for the two together.
The question is how to produce a figure with two different matrices displayed via heatmap or some other function to do the same?
(as an extra side, could you also explain the context of the 'using' statement and how it relates to the 'backend'?)
The easiest way is to make a Vector of heatmaps, then plot those
using Plots
hms = [heatmap(randn(10,10)) for i in 1:16];
plot(hms..., layout = (4,4), colorbar = false)
The using statement calls the Plots library. The "backend" is another package, loaded by Plots, that does the actual plotting. Plots itself has no plotting capabilities - it translates the plot call to a plot call for the backend package.
Explanation of the code above:
Plotting with Plots is a two-step process. 1: plot generates a Plot object with all the information for the plot; 2: when a Plot object is returned to the console, it automatically calls julia´s display function, which then generates the plot. But you can do other things with the Plot object first, like put it in an array.
The heatmap call is a short form of plot(randn(10,10), seriestype = :heatmap), so it just creates a Plot object. 16 Plot objects are stored in the vector.
Passing a number of Plot objects to plot creates a new, larger Plot, with each of the incoming Plot objects as subplots. The splat operator ... simply passes each element of the Array{Plot} to plot as an individual argument.

How can I set the number of ticks in Julia using Pyplot?

I am struggling to 'translate' the instructions I find for Python to the use of Pyplot in Julia. This must be a simple question, but do you know how to set the number of ticks in a plot in Julia using Pyplot?
If you have
x = [1,2,3,4,5]
y = [1,3,6,8,11]
you can
PyPlot.plot(x,y)
which draws the plot
and then do
PyPlot.xticks([1,3,5])
for tics at 1,3 and 5 on the x-axis
PyPlot.yticks([1,6,11])
for tics at 1,6 and 11 on the y-axis
Tic spacing
if you want fx 4 tics and want it evenly spaced and dont mind Floats, you can do
collect(linspace(x[1], x[end], 4).
If you need the tics to be integers and you want 4 tics, you can do
collect(x[1]:div(x[end],4):x[end])
Edit
Maybe this wont belong here but atleast you'll see it...
whenever you're looking for a method that's supposed to be in a module X you can find these methods by typing in the REPL X. + TAB key
to clarify, if you want to search a module for a method you suspect starts with an x, like xticts, in the REPL (terminal/shell) do
PyPlot.x
and press TAB twice and you'll see
julia> PyPlot.x
xkcd xlabel xlim xscale xticks
and if you're not sure exactly how the method works, fx its arguments, and there isnt any help available, you can call
methods(PyPlot.xticks)
to see every "version" that method has
Bonus
The module for all the standard methods, like maximum, vcat etc is Base
After some trying and searching, I found a way to do it. One can just set the number of bins that should be on each axis. Here is a minimal example:
using PyPlot
x = linspace(0, 10, 200)
y = sin(x)
fig, ax = subplots()
ax[:plot](x, y, "r-", linewidth=2, label="sine function", alpha=0.6)
ax[:legend](loc="upper center")
ax[:locator_params](axis ="y", nbins=4)
The last line specifies the number of bins that should be used on the y-axis. Leaving the argument axis unspecified will set that option for both axis at the same value.

matplotlib: working with range in x-axis

I'm trying to do a basic line graph here, but I can't seem to figure out how to adjust my x axis.
And here is the error I get when I try adjusting my range.
from pylab import *
plot ( range(0,11),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' )
plot ( range(0,11),[12,5,33,2,4,5,3,3,22,10],'o-',label='sample2' )
xlabel('x axis')
ylabel('y axis')
title('my sample graphs')
legend(('sample1','sample2'))
savefig("sampleg.png",dpi=(640/8))
show()
File "C:\Python26\lib\site-packages\matplotlib\axes.py", line 228, in _xy_from_xy
raise ValueError("x and y must have same first dimension")
ValueError: x and y must have same first dimension
I want my range to be a list of strings: ["12/1/2007","12/1/2008", "12/1/2009","12/1/2010"]
Any suggestions?
Honestly, I found the code online and was trying to rewrite it to properly understand it. I think I'm going to start from scratch so that I know what I'm doing but I need help on where to start.
I posted another question which explains what I want to do here:
Using PyLab to create a 2D graph from two separate lists
range(0,11) should be range(0,10).
In addition to Steve's observation: If your points are always some y-value at the same consecutive integer x's, matplotlib makes the range even implicit.
plot([9,4,5,2,3,5,7,12,2,3],'.-',label='sample1')