how to wrap text in ggplot for facet_grid labels - word-wrap

I have been searching how to wrap text. It seems there should be a way to use labeller = label_wrap_gen(3) but I keep getting an error:
--- Error in margins(vars, margins) : unused argument (margins)
Here is part of my code:
#simpson by protected status for domain FKNMS
ggplot(data = fk_strata_abun_diversity, aes(x = YEAR)) +
geom_point(aes(y = strata_simpson, color = "strata_simpson"),color = "blue") +
geom_line(aes(y = strata_simpson, color = "strata_simpson"), color = "blue") +
facet_grid(STRAT ~ protected_status,
labeller = labeller(.rows = strata_names, .cols = protected_status_names),
label_wrap_gen(width = 2)) + #error: in margins(vars, margins) : unused argument (margins) ??
labs(x = "Year", y = "Effective Number of Species") +
ggtitle("Simpson Diveristy of Reef Fish in the Florida Keys by Strata") +
theme(plot.title = element_text(hjust = 0.5, face = 'bold', size = 12)) +
scale_x_continuous(limits = c(1999, 2016), breaks = c(1999:2016)) +
scale_y_continuous(limits= c(0, 25), breaks = c(5,10,15,20,25))
Thank you in advance for the help

I found labeller = labeller(label_wrap_gen(width = 2... does not wrap.
Try
facet_grid(STRAT ~ protected_status,
labeller = label_wrap_gen(width = 2, multi_line = TRUE))

the following will work for facet_grid() and facet_wrap():
facet_grid(labeller = labeller(facet_category = label_wrap_gen(width = 16)))
where facet_category is the faceting variable to modify and width sets the maximum number of characters before wrapping.
multi_line is only needed if you have specified multiple factors in your faceting formula (eg. ~first + second)

Related

Is there a way that I can solve or stop this error problem in cardinality_threshold?

I have about 17 soil variables that I'd like to run correlations with elevations, temperature and rainfall against species richness and abundance. I have 39 plots (rows) and the columns contain, environmental variables such as elevation, abundance, species richness, temperature, rainfall and then the list of soil variables (17 columns). Below is my script.
Is there a problem with my script or is it the laptop compatibility of the mac I am using? Please help. Thanks
After running the codes, I am getting this error:
Error in stop_if_high_cardinality(data, columns, cardinality_threshold) :
Column 'pH' has more levels (24) than the threshold (15) allowed.
Please remove the column or increase the 'cardinality_threshold' parameter. Increasing the cardinality_threshold may produce long processing times
GGally::ggpairs(
na.omit(nfi_nontree_soilclim_data[, c(11:18)]),
upper = list(
continuous = wrap(
custom_ggally_cor,
method = "spearman", exact = FALSE,
size = 2.5, col = "black", family = "serif", digits = 2
), combo = "box_no_facet", discrete = "count", na = "na"
),
lower = list(
continuous = wrap(
ggally_smooth,
method = "loess", formula = y ~ x,
se = F, lwd = 3, col = "red", shrink = T
), combo = "facethist", discrete = "facetbar", na = "na"
),
diag = list(
continuous = wrap(
ggally_densityDiag,
col = "darkgrey", lwd = .1,
stat = "density", fill = "darkgrey"
), continuous = "densityDiag", na = "naDiag"
), axisLabels = c("show")
) + theme_bw() + theme(
text = element_text(family = "serif", size = 4),
axis.text = element_text(family = "serif", size = 4),
panel.grid = element_blank()
)```
This error is a built-in stop because the default parameter is set to only allow 15 levels of a variable to be displayed in one graph. You have 24 levels for one of your variables, so you can either adjust the parameter, i.e., the cardinality_threshold, to that value of 24 or set it to NULL. Null may be more generalizable if the value of 24 isn't always the same. But in general, that number of levels depicted at once is going to be discouraged and have these stop-limits.
library(GGally)
data(iris)
Create data that has factor of more than 15 levels
iris$group = as.factor(sample(sample(letters,16), 150, replace = TRUE))
Just demonstrating that either entry can work
ggpairs(iris, cardinality_threshold = 16)
ggpairs(iris, cardinality_threshold = NULL)

How to properly process images with mixed noise types

The picture with noise is like this.
Noised picture: Image3.bmp
I was doing image processing in MatLab with some built-in and self-implemented filters.
I have already tried a combination of bilateral, median and gaussian. bilateral and gaussian code are at the end of this post.
img3 = double(imread('Image3.bmp')); % this is the noised image
lena = double(imread('lena_gray.jpg')); % this is the original one
img3_com = bilateral(img3, 3, 2, 80);
img3_com = medfilt2(img3_com, [3 3], 'symmetric');
img3_com = gaussian(img3_com, 3, 0.5);
img3_com = bilateral(double(img3_com), 6, 100, 13);
SNR3_com = snr(img3_com,img3_com - lena); % 17.1107
However, the result is not promising with SNR of only 17.11.
Filtered image: img3_com
The original picture is like this.
Clean original image: lena_gray.jpg
Could you please give me any possible ideas about how to process it? Like what noise generators generated the noised image and what filtering methods or image processing method I can use to deal with it. Appreciate!!!
My bilateral function bilateral.m
function img_new = bilateral(img_gray, window, sigmaS, sigmaI)
imgSize = size(img_gray);
img_new = zeros(imgSize);
for i = 1:imgSize(1)
for j = 1:imgSize(2)
sum = 0;
simiSum = 0;
for a = -window:window
for b = -window:window
x = i + a;
y = j + b;
p = img_gray(i,j);
q = 0;
if x < 1 || y < 1 || x > imgSize(1) || y > imgSize(2)
% q=0;
continue;
else
q = img_gray(x,y);
end
gaussianFilter = exp( - double((a)^2 + (b)^2)/ (2 * sigmaS^2 ) - (double(p-q)^2)/ (2 * sigmaI^2 ));
% gaussianFilter = gaussian((a^2 + b^2)^(1/2), sigma) * gaussian(abs(p-q), sigma);
sum = sum + gaussianFilter * q;
simiSum = simiSum + gaussianFilter;
end
end
img_new(i,j) = sum/simiSum;
end
end
% disp SNR
lena = double(imread('lena_gray.jpg'));
SNR1_4_ = snr(img_new,img_new - lena);
disp(SNR1_4_);
My gaussian implementation gaussian.m
function img_gau = gaussian(img, hsize, sigma)
h = fspecial('gaussian', hsize, sigma);
img_gau = conv2(img,h,'same');
% disp SNR
lena = double(imread('lena_gray.jpg'));
SNR1_4_ = snr(img_gau,img_gau - lena);
disp(SNR1_4_);

How to avoid overlapping between title and labels in Matlab's pie chart?

I'm using the next code to plot in a pie chart the percentage of values in a matrix that are greater/smaller than 1. The thing is that when I want to put the title above the graph, it overlaps with the label of one of the groups.
I tried replacing it with text() but it didn't worked, and Documentation on pie say nothing to this. How can I avoid this overlap?
eigen = []; % Modes array
c2 = 170; % Sound speed divided by 2
%% Room dimensions
lx = 5.74;
ly = 8.1;
lz = 4.66;
i = 1; % Index for modes array
for nz = 0:50
for ny = 0:50
for nx = 0:50
aux = c2 * sqrt((nx/lx)^2+(ny/ly)^2+(nz/lz)^2);
if aux < 400 %% If value is into our range of interest
eigen(i) = aux;
i=i+1;
end
end
end
end
eigen = round(sort(eigen'),1);
eigen
% dif = eigen(2:end)-eigen(1:end-1); % Distance between modes
x = 0; %% dif >= 1
y = 0; %% dif <= 1
dif = [];
for i=2:length(eigen)
if eigen(i)-eigen(i-1) >= 1
x = x+1;
else
y = y+1;
end
end
figure
dif = [x,y];
explode = [1 1];
graf = pie(dif,explode);
hText = findobj(graf,'Type','text');
percentValues = get(hText,'String');
txt = {'Smaller than 1 Hz: ';'Greater than 1 Hz: '};
combinedtxt = strcat(txt,percentValues);
oldExtents_cell = get(hText,'Extent');
oldExtents = cell2mat(oldExtents_cell);
hText(1).String = combinedtxt(1);
hText(2).String = combinedtxt(2);
title('Distance between modes')
You can rotate the pie chart so that the figure look better. Further, you can use position to allocate your text as follows,
figure
dif = [x,y];
explode = [1 1];
graf = pie(dif,explode);
hText = findobj(graf,'Type','text');
percentValues = get(hText,'String');
txt = {'Smaller than 1 Hz: ';'Greater than 1 Hz: '};
combinedtxt = strcat(txt,percentValues);
oldExtents_cell = get(hText,'Extent');
oldExtents = cell2mat(oldExtents_cell);
hText(1).String = combinedtxt(1);
hText(2).String = combinedtxt(2);
view([90 90]) % this is to rotate the chart
textPositions_cell = get(hText,{'Position'});
textPositions = cell2mat(textPositions_cell);
textPositions(:,1) = textPositions(:,1) + 0.2; % replace 0.2 with any offset value you want
hText(1).Position = textPositions(1,:);
hText(2).Position = textPositions(2,:);
title('Distance between modes')
You can change only the text position (without rotation) by deleting view command.

Reduce the calculation time for the matlab code

To calculate an enhancement function for an input image I have written the following piece of code:
Ig = rgb2gray(imread('test.png'));
N = numel(Ig);
meanTotal = mean2(Ig);
[row,cal] = size(Ig);
IgTransformed = Ig;
n = 3;
a = 1;
b = 1;
c = 1;
k = 1;
for ii=2:row-1
for jj=2:cal-1
window = Ig(ii-1:ii+1,jj-1:jj+1);
IgTransformed(ii,jj) = ((k*meanTotal)/(std2(window) + b))*abs(Ig(ii,jj)-c*mean2(window)) + mean2(window).^a;
end
end
How can I reduce the calculation time?
Obviously, one of the factors is the small window (3x3) that should be made in the loop each time.
Here you go -
Igd = double(Ig);
std2v = colfilt(Igd, [3 3], 'sliding', #std);
mean2v = conv2(Igd,ones(3),'same')/9;
Ig_out = uint8((k*meanTotal)./(std2v + b).*abs(Igd-cal*mean2v) + mean2v.^a);
This will change the boundary elements too, which if not desired could be set back to the original ones with few additional steps, like so -
Ig_out(:,[1 end]) = Ig(:,[1 end])
Ig_out([1 end],:) = Ig([1 end],:)

Matlab SVM for Image Classification

I am using SVM function of Matlab to classify images that are read from a folder. What I want to do is first read 20 images from the folder, then use these to train the SVM, and then give a new image as input to decide whether this input image falls into the same category of these 20 training images or not. If it is, then the classification result should give me 1, if not, then I expect to receive -1.
Up to now, my written code is as follows:
imagefiles = dir('*.jpg');
nfiles = 20;
for i = 1:nfiles
currentfilename = imagefiles(i).name;
currentimage = imread(currentfilename);
images{i} = currentimage;
images{i} = im2double(images{i});
images{i} = rgb2gray(images{i});
images{i} = imresize(images{i},[200 200]);
images{i} = reshape(images{i}', 1, size(images{i},1)*size(images{i},2));
end
trainData = zeros(nfiles, 40000);
for ii=1:nfiles
trainData(ii,:) = images{ii};
end
class = [1 1 1 1 1 1 1 1 -1 -1 -1 -1 -1 -1 1 1 1 1 1 1];
SVMStruct = svmtrain (trainData, class);
inputImg = imread('testImg.jpg');
inputImg = im2double(inputImg);
inputImg = rgb2gray(inputImg);
inputImg = imresize(inputImg, [200 200]);
inputImg = reshape (inputImg', 1, size(inputImg,1)*size(inputImg,2));
result = svmclassify(SVMStruct, inputImg);
Since the images are read by series from the folder, so camethe cell images. Then I converted them to grayscale as shown in the code, and resized them, since those images were NOT of same size. Thus after this step, I had 20 images, all of each with size 200x200. And at last, I gave these to serve as my training dataset, with 20 rows, and 200x200 columns. I checked all of these size results, and they seemed to work fine. But right now the only problem is, no matter what kind of input image I give it to predict, it always gives me a result as 1, even for those very different images. Seems like it is not working correctly. Could someone help me check out where should be the problem here? I couldn't find any explanation from the existing sources on the internet. Thanks in advance.
Here is a function to read all images that may help you
function X = ReadImgs(Folder,ImgType)
Imgs = dir(fullfile(Folder, ImgType));
NumImgs = size(Imgs,1);
image = double(imread(fullfile(Folder, Imgs(1).name)));
X = zeros([NumImgs size(image)]);
for i=1:NumImgs,
img = double(imread(fullfile(Folder, Imgs(i).name)));
if (size(image,3) == 1)
X(i,:,:) = img;
else
X(i,:,:,:) = img;
end
end
Source: http://computervisionblog.wordpress.com/2011/04/13/matlab-read-all-images-from-a-folder-everything-starts-here/
this is should be works in MATLAB
clear all;
clc;
folder = 'gambar 1';
dirImage = dir( folder );
numData = size(dirImage,1);
M ={} ;
% read image
for i=1:numData
nama = dirImage(i).name;
if regexp(nama, '(lion|tiger)-[0-9]{1,2}.jpg')
B = cell(1,2);
if regexp(nama, 'lion-[0-9]{1,2}.jpg')
B{1,1} = double(imread([folder, '/', nama]));
B{1,2} = 1;
elseif regexp(nama, 'tiger-[0-9]{1,2}.jpg')
B{1,1} = double(imread([folder, '/', nama]));
B{1,2} = -1;
end
M = cat(1,M,B);
end
end
% convert image holder from cell to array
numDataTrain = size(M,1);
class = zeros(numDataTrain,1);
arrayImage = zeros(numDataTrain, 300 * 300);
for i=1:numDataTrain
im = M{i,1} ;
im = rgb2gray(im);
im = imresize(im, [300 300]);
im = reshape(im', 1, 300*300);
arrayImage(i,:) = im;
class(i) = M{i,2};
end
SVMStruct = svmtrain(arrayImage, class);
% test for lion
lionTest = double(imread('gambar 1/lion-test.jpg' ));
lionTest = rgb2gray(lionTest);
lionTest = imresize(lionTest, [300 300]);
lionTest = reshape(lionTest',1, 300*300);
result = svmclassify(SVMStruct, lionTest);
result
https://github.com/gunungloli666/svm-test

Resources