I am a newbie of xaringan and trying to draw some pictures using tikz package.
I was wondering how to run tikz in xaringan slides.
My codes are:
---
title: "Econ"
subtitle: "Lecture 1"
author: "Instructor"
institute: "College"
date: "`r Sys.Date()`"
output:
xaringan::moon_reader:
css: [default, metropolis, metropolis-fonts, "styles.css"]
lib_dir: libs
nature:
highlightStyle: arta
highlightLines: true
countIncrementalSlides: false
---
```{r,engine='tikz'}
\tikzset{every picture/.style={line width=0.75pt}} %set default line width to 0.75pt
\begin{tikzpicture}[x=0.75pt,y=0.75pt,yscale=-1,xscale=1]
%uncomment if require: \path (0,379); %set diagram left start at 0, and has height of 379
%Rounded Rect [id:dp1857476422681199]
\draw [fill={rgb, 255:red, 241; green, 192; blue, 192 } ,fill opacity=1 ] (228,123) .. controls (228,114.16) and (235.16,107) .. (244,107) -- (343,107) .. controls (351.84,107) and (359,114.16) .. (359,123) -- (359,171) .. controls (359,179.84) and (351.84,187) .. (343,187) -- (244,187) .. controls (235.16,187) and (228,179.84) .. (228,171) -- cycle ;
%Shape: Rectangle [id:dp08440493370073976]
\draw [fill={rgb, 255:red, 226; green, 233; blue, 201 } ,fill opacity=1 ] (415,115) -- (525,115) -- (525,179) -- (415,179) -- cycle ;
%Rounded Single Corner Rect [id:dp01343887372328001]
\draw [fill={rgb, 255:red, 0; green, 0; blue, 0 } ,fill opacity=0.05 ] (64,129.52) .. controls (64,122.27) and (69.87,116.4) .. (77.12,116.4) -- (170,116.4) -- (170,182) -- (64,182) -- cycle ;
%Straight Lines [id:da9440635149995973]
\draw (171,144) -- (218,144) ;
\draw [shift={(221,144)}, rotate = 180] [fill={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.08] [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle ;
%Straight Lines [id:da7316344569835018]
\draw (361,145) -- (405,145) ;
\draw [shift={(408,145)}, rotate = 180] [fill={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.08] [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle ;
%Curve Lines [id:da512763546270846]
\draw (415,179) .. controls (380.35,241.37) and (217.31,242.97) .. (171.36,183.81) ;
\draw [shift={(170,182)}, rotate = 54.2] [fill={rgb, 255:red, 0; green, 0; blue, 0 } ][line width=0.08] [draw opacity=0] (10.72,-5.15) -- (0,0) -- (10.72,5.15) -- (7.12,0) -- cycle ;
\draw (280.56,238.98) -- (311.32,217.88)(282.27,217.6) -- (309.61,239.25) ;
% Text Node
\draw (420,125) node [anchor=north west][inner sep=0.75pt] [align=left] {{\fontfamily{ptm}\selectfont \textit{\textbf{y} }}\\{\fontfamily{ptm}\selectfont \textit{variables}}};
% Text Node
\draw (75,129) node [anchor=north west][inner sep=0.75pt] [align=left] {{\fontfamily{ptm}\selectfont \textit{\textbf{x}}}\\{\fontfamily{ptm}\selectfont \textit{variables}}};
% Text Node
\draw (271,138.4) node [anchor=north west][inner sep=0.75pt] {$function$};
\end{tikzpicture}
```
My code generates the following error with the same weird outcome, which is just the copy of my codes.
Error in if (to_svg) tinytex::latexmk(texf, "latex") else tinytex::latexmk(texf) : argument is of length zero
You are having the error Error in if (to_svg) tinytex::latexmk(texf, "latex") else tinytex::latexmk(texf) : argument is of length zero, due to most probably, you don't have the {tinytex} package installed. Because tikz engine requires the {tinytex} package to compile TikZ graphics to other foramts (e.g., svg or png).
So try installing the {tinytex} package at first. See here how to do that.
Then also add the echo=FALSE in chunk option.
Related
Just looking forward a solution to remove empty values from a column which has values as a list in a sense where we are already replacing some strings beforehand, where it's a column of string representation of lists.
In df.color we are Just replacing *._Blue with empty string:
Example DataFrame:
df = pd.DataFrame({ 'Bird': ["parrot", "Eagle", "Seagull"], 'color': [ "['Light_Blue','Green','Dark_Blue']", "['Sky_Blue','Black','White', 'Yellow','Gray']", "['White','Jet_Blue','Pink', 'Tan','Brown', 'Purple']"] })
>>> df
Bird color
0 parrot ['Light_Blue','Green','Dark_Blue']
1 Eagle ['Sky_Blue','Black','White', 'Yellow','Gray']
2 Seagull ['White','Jet_Blue','Pink', 'Tan','Brown', 'Pu...
Result of above DF:
>>> df['color'].str.replace(r'\w+_Blue\b', '')
0 ['','Green','']
1 ['','Black','White', 'Yellow','Gray']
2 ['White','','Pink', 'Tan','Brown', 'Purple']
Name: color, dtype: object
Usually in python it easily been done as follows..
>>> lst = ['','Green','']
>>> [x for x in lst if x]
['Green']
I'm afraid if something like below can be done.
df.color.mask(df == ' ')
You can using the explode(pandas 0.25.0) then concat the list back
df['color'].str.replace(r'\w+_Blue\b', '').explode().loc[lambda x : x!=''].groupby(level=0).apply(list)
You don't have a column of lists, you have a column that contains string representation of lists. You can do this all in a single step using ast.literal_eval and str.endswith. I would use a list-comprehension here which should be faster than apply
import ast
fixed = [
[el for el in lst if not el.endswith("Blue")]
for lst in df['color'].apply(ast.literal_eval)
]
df.assign(color=fixed)
Bird color
0 parrot [Green]
1 Eagle [Black, White, Yellow, Gray]
2 Seagull [White, Pink, Tan, Brown, Purple]
Another way using filter and apply:
(df['color'].str.replace(r'\w+_Blue\b', '')
.apply(lambda x: list(filter(bool, ast.literal_eval(x)))))
0 [Green]
1 [Black, White, Yellow, Gray]
2 [White, Pink, Tan, Brown, Purple]
I defined a lot of "object" like this:
Each of them has properties, like color, size, position ecc.
How can I store them in a list and assign to them a unique identifier?
I make them as follow:
let tmploop 0
while [tmploop < 20] [
makecell tmploop
set tmploop tmploop + 1
]
to makecell [ n ]
let head random 360
let jum random 20
create-turtles n
[ set shape "circle"
set color green
set size 2
set heading head
jump jum]
create-turtles n
[ set shape "circle"
set color red
set size 1.33
set heading head
jump jum]
create-turtles n
[ set shape "circle"
set color gray
set size 0.66
set heading head
jump jum]
end
I would like to refer to each ring of the same cell, for example.
Should I use something like breed or do you have other ideas?
I would like to extract the labels from the 2D Binary image I get using the following code:
image2DThresh = sitk.Threshold(image2D, lower=stats.GetMinimum(), upper=127.500)
cca = sitk.ConnectedComponentImageFilter()
cca_image = cca.Execute(2D_Slice)
# Get the shape statistics of the labels using
labelStats = sitk.LabelShapeStatisticsImageFilter()
The basic idea is to find the mean intensity, area of ROI and min/max indexes of the label in the main image. What I am trying to do is binarizing the image with Threshold Filter, then running CCA on this to get all the labels. Then I use the LabelShapeStatisticsImageFilter() to get the physical attributes of every label (except label 0 of course) and check if the label meets the conditions. The problem is i am not able to get the average intensity in the main image where the label is. That is why I suggest using LabelIntensityStatisticsFilter, which however for python 2.7, SimpleITK 0.10 isn't available.
The two filters which you may be interested in are the "LabelStatisticsImageFilter" and the "LabelIntensityStatisticsImageFilter". These are both available in SimpleITK 0.10, if not you have a distribution problem. Both filters compute the mean, but the later computes a bounding box and many more advanced statistics.
Usage would go something like this:
In [1]: import SimpleITK as sitk
In [2]: print sitk.Version()
SimpleITK Version: 0.10.0 (ITK 4.10)
Compiled: Aug 16 2016 17:21:32
In [3]: img = sitk.ReadImage("cthead1.png")
In [4]: cc = sitk.ConnectedComponent(img>100)
In [5]: stats = sitk.LabelIntensityStatisticsImageFilter()
In [6]: stats.Execute(cc,img)
Out[6]: <SimpleITK.SimpleITK.Image; proxy of <Swig Object of type 'std::vector< itk::simple::Image >::value_type *' at 0x2a6b540> >
In [7]: for l in stats.GetLabels():
...: print("Label: {0} -> Mean: {1} Size: {2}".format(l, stats.GetMean(l), stats.GetPhysicalSize(l)))
...:
Label: 1 -> Mean: 157.494210868 Size: 3643.8348071
Label: 2 -> Mean: 151.347826087 Size: 2.86239969136
Label: 3 -> Mean: 123.75 Size: 0.497808641975
Label: 4 -> Mean: 106.0 Size: 0.248904320988
Label: 5 -> Mean: 104.0 Size: 0.124452160494
Label: 6 -> Mean: 106.0 Size: 0.124452160494
Label: 7 -> Mean: 103.0 Size: 0.124452160494
Label: 8 -> Mean: 121.5 Size: 1.49342592593
Label: 9 -> Mean: 106.0 Size: 0.124452160494
In stead of printing you could create lists of labels to preserve or to relabel to 0 (erase). The ChangeLabelImageFilter can then be used to apply this change to the label image.
The combination of thresholding, statistics, and label section is a power segmentation approach which can be used and customized for many tasks. It also serves as a starting point for more complication methods.
So I solved the problem using numpy. I'm posting the code, may be it helps someone else in the future!
def get_label(ccaimage, label, image2D):
# labelImage is the mask for a particular label
labelImage = sitk.Threshold(ccaimage, lower=label, upper=label)
#sitk_show(labelImage)
# get image as array
labelImageArray = sitk.GetArrayFromImage(labelImage)
image2Darray = sitk.GetArrayFromImage(image2D)
# ROI_1 is the minimum in the original image where the mask is equal to label
ROI_1 = image2Darray == np.min(image2Darray[labelImageArray == label])
plt.imshow(ROI_1)
plt.show()
# ROI_2 is the mask image
ROI_2 = labelImageArray == label
plt.imshow(ROI_2)
plt.show()
# AND gives me only those pixels which satisfy both conditions.
ROI = np.logical_and(image2Darray == np.min(image2Darray[labelImageArray == label]), labelImageArray == label )
avg = np.mean(image2Darray[labelImageArray == label])
print np.min(image2Darray[labelImageArray == label])
print np.where(ROI)
plt.imshow(ROI)
plt.show()
My objective is to have an agentset (named ships) hatch at another agentset (named ports and listed in index) containing 2 locations representing the start and end of a pathway. To go- start moving ships/ heading towards a third agentset (called waypoints and listed in index1) in their given order.
However, if a port is closer to the current waypoint than another waypoint- move to port instead. Once the ships have reached the other port, I would also like them to stop.
Currently I have the model working with only two agentsets (ships and ports) however I would like to include a third set(called waypoints) to prevent ships from hatching at all locations(ports and waypoints) and to have the ships move in a sequential order by traveling along the waypoints (like stepping stones) before reaching the beginning or the end (ports).
Here is an example of my code:
breed [ships ship]
breed [ports port]
breed [waypoints waypoint]
ships-own [target-port
current-port]
to setup
ca
let index 0
create-ports 2
[ let loc item index [ [0 -32] [32 0] ]
setxy (item 0 loc) (item 1 loc)
set index index + 1
set shape "circle"
set size 2
set color red - 1]
let index1 0
create-waypoints 2
[let loc item index1 [[12 -3] [14 -26]]
setxy (item 0 loc) (item 1 loc)
set index1 index1 + 1
set shape "circle"
set size 1
set color red - 1]
ask ports
[ let s who
hatch-ships 1
[ set current-port s
set size 1
set color red
pen-down
set pen-size 1
set target-port min-one-of ports with [ who != s] [distance myself]
set heading towards target-port
]
]
reset-ticks
end
to go
;(obey-elevation)
ask ships
[ if (distance target-port = 0)
[ let other_ports no-turtles
ask target-port [set other_ports (other ports)]
set target-port min-one-of other_ports [distance myself]
face target-port
]
ifelse (distance target-port < 1)
[ move-to target-port
]
[fd 1
]
]
tick
end
Any help would be greatly appreciated.
New to R. Looking to replace the entire string if there is a partial match.
d = c("SDS0G2 Blue", "Blue SSC2CWA3", "Blue SA2M1GC", "SA5 Blue CSQ5")
gsub("Blue", "Red", d, ignore.case = FALSE, fixed = FALSE)
Output: "SDS0G2 Red" "Red SSC2CWA3" "Red SA2M1GC" "SA5 Red CSQ5"
Desired Output: “Red” “Red” “Red” “Red”
Any help in solving this is truly appreciated.
I'd suggest using grepl to find the indices and replace those indices with "Red":
d = c("SDS0G2 Blue", "Blue SSC2CWA3", "Blue SA2M1GC", "SA5 Blue CSQ5", "ABCDE")
d[grepl("Blue", d, ignore.case=FALSE)] <- "Red"
d
# [1] "Red" "Red" "Red" "Red" "ABCDE"
If you did want to keep the variable as a factor and replace multiple partial matches at once, the following function will work (example from another question).
clrs <- c("blue", "light blue", "red", "rose", "ruby", "yellow", "green", "black", "brown", "royal blue")
dfx <- data.frame(colors1=clrs, colors2 = clrs, Amount=sample(100,10))
# Function to replace levels with regex matching
make_levels <- function(.f, patterns, replacement = NULL, ignore.case = FALSE) {
lvls <- levels(.f)
# Replacements can be listed in the replacement argument, taken as names in patterns, or the patterns themselves.
if(is.null(replacement)) {
if(is.null(names(patterns)))
replacement <- patterns
else
replacement <- names(patterns)
}
# Find matching levels
lvl_match <- setNames(vector("list", length = length(patterns)), replacement)
for(i in seq_along(patterns))
lvl_match[[replacement[i]]] <- grep(patterns[i], lvls, ignore.case = ignore.case, value = TRUE)
# Append other non-matching levels
lvl_other <- setdiff(lvls, unlist(lvl_match))
lvl_all <- append(
lvl_match,
setNames(as.list(lvl_other), lvl_other)
)
return(lvl_all)
}
# Replace levels
levels(dfx$colors2) <- make_levels(.f = dfx$colors2, patterns = c(Blue = "blue", Red = "red|rose|ruby"))
dfx
#> colors1 colors2 Amount
#> 1 blue Blue 75
#> 2 light blue Blue 55
#> 3 red Red 47
#> 4 rose Red 83
#> 5 ruby Red 56
#> 6 yellow yellow 10
#> 7 green green 25
#> 8 black black 29
#> 9 brown brown 23
#> 10 royal blue Blue 24
Created on 2020-04-18 by the reprex package (v0.3.0)