I need help adding tick marks to my barplot. I would like an X-axis with tick marks in intervals of 100. I would also like to add a vertical red line at X=1350. How can I add that to the following code:
H <- c(1350, 1436) # Create the data for the chart, cont3.#
M <- c(
"Target
Attendance",
"Actual
Attendance"
)
c <-barplot(H, col =c("slategray3","dodgerblue4" ),
names.arg = M, horiz = TRUE,
family="Arial", border = NA,
xlim = range(0,1600),
axes = TRUE, las=1)
One can use the axis() and abline() functions to modify the base graphics:
barplot(H, col =c("slategray3","dodgerblue4" ),
names.arg = M, horiz = TRUE,
family="Arial", border = NA,
xlim = range(0,1600),
axes = FALSE, las=1)
axis(1, at=seq(0, 1500, 100))
abline(v=1350, col="red")
Add the "lwd=" option to the abline function to change the line's width.
Related
I want to be able to select a line on the plot by clicking on it. Ideally, when I click on any line, the number of that line will appear on the screen.
I wrote my code based on the tutorial, but there is no example with lines, so I did what I did. https://docs.makie.org/v0.19/documentation/events/index.html#point_picking
At the moment I have no idea what these numbers are telling me and why. They are not even coordinates of clicked points.
P.S. Actually it is just a starting point. I want to create event interaction on series and topoplots. But for now it would be great to find out the basics.
f = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98), resolution = (1500, 700))
ax = Axis(f[1, 1], xlabel = "Time [s]", ylabel = "Voltage amplitude [µV]")
N = 1:length(pos)
positions = Observable(rand(Point2f, 10))
xs = 0:0.01:10
ys = 0.5 .* sin.(xs)
lines!(xs, ys)
lines!(xs, ys * 2)
hidedecorations!(ax, label = false, ticks = false, ticklabels = false)
hidespines!(ax, :t, :r)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
i = Observable(0)
on(events(f).mousebutton, priority = 2) do event
if event.button == Mouse.left && event.action == Mouse.press
plt, i[] = pick(f)
str = lift(i -> "$(i)", i)
text!(ax, 1, -0.5, text = str, align = (:center, :center))
end
end
f
Below are some examples of the interaction between clicking and the number displayed (the red dot is where I click).
Check out the mouseposition variable here:
https://docs.makie.org/stable/api/#Events
or the registerInteraction! function here:
https://docs.makie.org/v0.19/examples/blocks/axis/index.html#registering_and_deregistering_interactions
You can use them both as below:
using GLMakie
f = Figure(backgroundcolor = RGBf(0.98, 0.98, 0.98), resolution = (1500, 700))
ax = Axis(f[1, 1], xlabel = "Time [s]", ylabel = "Voltage amplitude [µV]")
#N = 1:length(pos)
positions = Observable(rand(Point2f, 10))
xs = 0:0.01:10
ys = 0.5 .* sin.(xs)
lines!(xs, ys)
lines!(xs, ys * 2)
hidedecorations!(ax, label = false, ticks = false, ticklabels = false)
hidespines!(ax, :t, :r)
hlines!(0, color = :gray, linewidth = 1)
vlines!(0, color = :gray, linewidth = 1)
register_interaction!(ax, :my_interaction) do event, axis
if event.type === MouseEventTypes.leftclick
println("Graph axis position: $(event.data)")
end
end
i = Observable(0)
on(events(f).mousebutton, priority = 2) do event
if event.button == Mouse.left && event.action == Mouse.press
plt, i[] = pick(f)
str = lift(i -> "$(i)", i)
text!(ax, 1, -0.5, text = str, align = (:center, :center))
#show mouseposition(f)
end
end
f
Note that for some reason (perhaps it sees the first click as a selection?) Makie does not start registering the interaction on the graph until the first click within the graph, unlike the clicks on the figure which are all shown even the first one.
I'm new here and also a beginner Python user. In this chart I was trying to make, I just need to format the blue labels into percentage with 2 decimal places and move them right next to the values at the end of the bars.
Here is the code:
index = np.arange(6)
fig, ax = plt.subplots(figsize=(10, 2))
list1x = list(dict(train['Outlet_Location_Type'].value_counts()).keys())
list1y = list(train['Outlet_Location_Type'].value_counts())
ax.barh(list1x, list1y, alpha=0.7,
# width = 0.5,
color=cm.Blues([i / 0.00525 for i in [ 0.00808, 0.0045, 0.00281]])
)
plt.rcParams.update({'font.size': 10})
rects = ax.patches
for i, label in enumerate(ii / 8325 * 100 for ii in list1y):
ax.text(label, i, str(label), size=10, ha='left', va='center', color = "blue")
for h, label in enumerate(list1y):
ax.text(label, h, label, size=10, ha='left', va='center')
ax.text(0, 1.02, 'Outlet Location Type Count', transform=ax.transAxes, size=12, weight=600, color='#777777')
ax.xaxis.set_ticks_position('bottom')
ax.tick_params(axis='x', colors='black', labelsize=9)
ax.set_axisbelow(True)
plt.xticks([])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
I think there could be data type issue causing the blue values to stay at the left side. I can't find the formatting solution to change them into percentage.
Thank you so much in advance!
This is the current code I have
sns.set_style("whitegrid",{'axes.spines.top': True, 'axes.spines.right': True,'axes.linewidth': 2, 'axes.edgecolor':'black'})
g = sns.JointGrid(x=station1,y=station2,data = df, xlim = xlim, ylim = ylim,space =1)
sns.set_style("whitegrid",{'axes.spines.top': True, 'axes.spines.right': True,'axes.linewidth': 2, 'axes.edgecolor':'black'})
g.plot_joint(sns.regplot, fit_reg = False, truncate = False, robust = False, label = 'regression', color = 'darkorange',)
g.plot_marginals(sns.histplot, kde = True, color = 'darkorange')
# g.ax_joint.legend({'Pearson_R: %.4f'%r, 'x_axis mean:%.3f; std:%.3f'%(d1.df[par_x][idx_1].mean(),d1.df[par_x][idx_1].std()),'y_axis mean:%.3f; std:%.3f'%(d2.df[par_y][idx_2].mean(),d2.df[par_y][idx_2].std())})
# g.ax_joint.legend({'y = %.3f x + %.3f \nR^2: %.4f'%(popt[0],popt[1],r**2)})
g.ax_joint.legend({'$R^2$:%.4f'%(r**2)}, loc = 'upper right')
g.ax_joint.plot(np.linspace(xlim[0],xlim[1],100),linear(np.linspace(xlim[0],xlim[1],100),1,0), linewidth = 0.7, ls = '-.', color = 'black')
I am trying to add spines to Top and left of a joint grid plot in seaborn, However, the best I am able to do is
2 sided plot
is there a way to add a boarder to the top and Right side of the main plot and add right top and left of the sub plots? Thanks.
I have a string chain of characters that I would like to display as big as possible within a rectangle frame, in a centered way. I know :
how many characters maximum can have my input
the dimensions of the rectangle
It has to :
find the best font size and displays the result.
Here is the MATLAB code
color = 'k';
txt = '1';
howManyCharMaximum = 7;
boxWidth = 250;
boxHeight = 100;
%% comput: Now I assume one char is as wide as tall
howManyChar = strlength(txt);
marginHoriz = mod(boxWidth,howManyCharMaximum); %in points
subRectangle.width = (boxWidth-marginHoriz)/howManyCharMaximum;
subRectangle.height = boxHeight;
[fontSize,idx] = min([subRectangle.width, subRectangle.height]); %the largest square that fits in a rectangle
%%
hFigure = figure('MenuBar', 'none', ...
'ToolBar', 'none', ...
'Units', 'points', ...
'Position', [0 0 boxWidth boxHeight], ... % x y from bottom left of screen to botleft of the fig
'Color', 'w');
hAxes = axes; hAxes.Visible = 'off';
%pos:=botleft vertex of the string
switch(idx)
case 1
x = floor((boxWidth-howManyChar*fontSize)/2);
y = floor((boxHeight-fontSize)/2);
case 2
addMarginHoriz = (subRectangle.width-subRectangle.height)*howManyCharMaximum;
x = floor((boxWidth-howManyChar*fontSize)/2);
y = 0;
end
hText = text(x, y, ...
txt, ...
'Units', 'points', ...
'FontSize', fontSize, ...
'HorizontalAlignment', 'left', ...
'VerticalAlignment', 'middle', ...
'Color', color);
But for some reasons I can't figure out, this is what it returns unfortunately -- a decentered character:
Would anyone know where I did a mistake pleaase ? By thanking you in advance.
I used normalized units for text as its lot easier to find the center and then it worked with the proper alignment. Note that a slight offset will still exist because actual figure grid has more space on left then right and at bottom then top. You can experimentally adjust it if you wish
color = 'k';
txt = '18998';
%howManyCharMaximum = 7; I didnt use this one
boxWidth = 250;
boxHeight = 100;
%% comput: Now I assume one char is as wide as tall
howManyChar = strlength(txt);
%marginHoriz = mod(boxWidth,howManyCharMaximum); %in points
subRectangle.width = (boxWidth)/howManyChar;
subRectangle.height = boxHeight;
[fontSize,idx] = min([subRectangle.width, subRectangle.height]); %the largest square that fits in a rectangle
%%
hFigure = figure('MenuBar', 'none', ...
'ToolBar', 'none', ...
'Units', 'points', ...
'Position', [0 0 boxWidth boxHeight], ... % x y from bottom left of screen to botleft of the fig
'Color', 'w');
hAxes = axes; hAxes.Visible = 'off';
%plot(0,0)
%pos:=botleft vertex of the string
x = floor(boxWidth/2);
y = floor(boxHeight/2)
hText = text(0.5, 0.5, ...
txt, ...
'Units', 'normalized', ...
'FontSize', fontSize, ...
'HorizontalAlignment', 'center', ...
'VerticalAlignment', 'middle', ...
'Color', color);
When I try to use the function below, I notice that my top row is missing the horizontal line in the plot. I've tracked this down to the line that specifies my rect dimensions, specifically how high and low it should be. Is there a parameter I can set so that the top line always appears? The code below does not have the top line..
Plot.Lines <- function(colCount, rowCount, cex){
colCount <- colCount # number per row
rowCount <- rowCount
plot( c(1,colCount), c(0,rowCount), type="n", ylab="", xlab="",
axes=FALSE, ylim=c(rowCount,0))
title("My Lines")
for (j in 0:(rowCount-1))
{
base <- j*colCount
remaining <- length(colors()) - base
RowSize <- ifelse(remaining < colCount, remaining, colCount)
for(i in 1:RowSize){
rect(i-0.5,j-0.5,i+0.5, j+0.5, border = "black", col = colors()[base + (1:RowSize)])
}
for(i in 1:RowSize){
text(x = i, y =j, labels = paste(base + i), cex =cex, col = "black")
}
}
}
Plot.Lines(25, 6, cex = 0.5)
However, if I change the line to:
rect(i-0.5,j-0.2,i+0.5, j+0.2, border = "black", col = colors()[base + (1:RowSize)])
then it works, although there is a space between the rows. Is there a way I an set it automatically given the colCount and the rowCount?
The top edge is cut off because it's beyond the plotting region. You can use par(xpd=TRUE) to allow plotting outside the inner region. Put this before your call to plot.