Variable opacity in a scatter 3D plotly plot
How to make a scatter3d look like a density plot in 3d?
I am trying to set the opacity (or some other variable) in a plot_ly scatter3d plot to use a value per point in the plot, with the values coming from a column in the dataframe. This in order to create a sort of 3d scatter density plot. In this case, the opacity column contains random values, but if this turns out to be possible, I want to make points LESS opaque when the amount of nearby points is high, and opaque when they are relatively isolated. Another approach to make this look like a density plot while perserving the scatter3d style is fine as well.
My attempts to play with opacity or alpha in the plot_ly code has failed and I could not find a working example.
The dataset can be downloaded from here: file
library(shiny)
library(plotly)
library(data.table)
mydf < read.csv("myshowdf.csv")
ui < fluidPage(
plotlyOutput('scatter', width = 800, height = 600)
)
server < function(input, output, session) {
output$scatter < renderPlotly({
ppl < plot_ly(mydf, x = ~FL.Red.Range, y = ~FL.Yellow.Range, z = ~SWS.Length, mode = 'markers',
color = ~sub.flow.FP1, marker = list(size = 4, opacity =mydf$opacity),
colors = c('blue', 'green', 'red', 'yellow'),
type = 'scatter3d', source = 'scatter') %>%
layout( autosize = F,
margin = list(l = 40, r = 20, b = 20, t = 40, pad = 4)
)
ppl$elementId < NULL
ppl
})
}
shinyApp(ui = ui, server = server)
See also questions close to this topic

2 yaxes Dumbbell ggplot2
I am quite new to R and programming in general. So please forgive my ignorance, I am trying to learn.
I have two sets of data and I would like to plot them against each other. Both have 27 rows and 3 columns; one set is called "range" and the other is called "rangePx". Column “Comp” has the different components, column “Min” is the minimum concentration in % and column “Max” is the maximum concentration in %.
I want to make a 2y axis dumbbell plot, with the y axis being the different components and x axis being the concentration.
I do manage to create 1 y axis dumbbell plot, but I have troubles to add the second y axis.
Here is a snap from the "range" data
head(range) # A tibble: 6 x 3 Comp Min Max <chr> <dbl> <dbl> 1 Methane 0.0100 100 2 Ethane 0.0100 65.0 3 Ethene 0.100 20.0 4 Propane 0.0100 40.0 5 Propene 0.100 6.00 6 Propadien 0.0500 2.00
and here is a snap from the "rangePx" data
head(rangePx) # A tibble: 6 x 3 Comp Min Max <chr> <dbl> <dbl> 1 Methane 50.0 100 2 Ethane 0.00800 14.0 3 Ethene 0 0 4 Propane 0.00800 8.00 5 Propene 0 0 6 Propadien 0 0
Here is the piece of code that I use:
library(ggplot2) library(ggalt) library(readxl) theme_set(theme_classic()) range < read_excel(range.xlsx) rangePx < read_excel(rangePx.xlsx") p < ggplot(range, aes(x=Max, xend=Min, y = Comp, group=Comp)) p < p + geom_dumbbell(color="blue") p px < ggplot(rangePx, aes(x=Max, xend=Min, y = Comp, group=Comp)) px < px + geom_dumbbell(color="green") p < p + geom_dumbbell(aes(y=px, color="red")) p
and here is the complain I get when I call
p
:Error: Aesthetics must be either length 1 or the same as the data (27): y, colour, x, xend, group
Here I saw a 6x3 data frame but my original data are 27x3
can anyone help me?
Thnx in advance

Trouble trying to clean a character vector in R data frame (UTF8 encoding issue)
I'm having some issues cleaning up a dataset after I manually extracted the data online  I'm guessing these are encoding issues. I have an issue trying to remove the "U+00A0" in the "Athlete" column cels along with the operator brackets. I looked up the corresponding UTF8 code and it's for "NoBreakSpace". I'm also not sure how to replace the other UTF8 characters to make the names legible  for e.g. getting U+008A to display as Š.
Subset of data
head2007decathlon < structure(list(Rank = 1:6, Athlete = c("<U+00A0>Roman <U+008A>ebrle<U+00A0>(CZE)", "<U+00A0>Maurice Smith<U+00A0>(JAM)", "<U+00A0>Dmitriy Karpov<U+00A0>(KAZ)", "<U+00A0>Aleksey Drozdov<U+00A0>(RUS)", "<U+00A0>Andr<e9> Niklaus<U+00A0>(GER)", "<U+00A0>Aleksey Sysoyev<U+00A0>(RUS)"), Total = c(8676L, 8644L, 8586L, 8475L, 8371L, 8357L), `100m` = c(11.04, 10.62, 10.7, 10.97, 11.12, 10.8), LJ = c(7.56, 7.5, 7.19, 7.25, 7.42, 7.01), SP = c(15.92, 17.32, 16.08, 16.49, 14.12, 16.16), HJ = c(2.12, 1.97, 2.06, 2.12, 2.06, 2.03), `400m` = c(48.8, 47.48, 47.44, 50, 49.4, 48.42), `110mh` = c(14.33, 13.91, 14.03, 14.76, 14.51, 14.59), DT = c(48.75, 52.36, 48.95, 48.62, 44.48, 49.76), PV = c(4.8, 4.8, 5, 5, 5.3, 4.9), JT = c(71.18, 53.61, 59.84, 65.51, 63.28, 57.75), `1500m` = c(275.32, 273.52, 279.68, 276.93, 272.5, 276.16), Year = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "2007", class = "factor"), Nationality = c(NA, NA, NA, NA, NA, NA)), .Names = c("Rank", "Athlete", "Total", "100m", "LJ", "SP", "HJ", "400m", "110mh", "DT", "PV", "JT", "1500m", "Year", "Nationality"), row.names = c(NA, 6L), class = c("tbl_df", "tbl", "data.frame"))
This is what I've tried so far to no success:
1) head2007decathlon$Athlete < gsub(pattern="\U00A0",replacement="",x=head2007decathlon$Athlete) 2) head2007decathlon$Athlete < gsub(pattern="<U00A0>",replacement="",x=head2007decathlon$Athlete) 3) head2007decathlon$Athlete < iconv(head2007decathlon$Athlete, from="UTF8", to="LATIN1") 4) Encoding(head2007decathlon$Athlete) < "UTF8" 5) head2007decathlon$Athlete< enc2utf8(head2007decathlon$Athlete)

Create a plot from boxplot.stats
Someone sent me a file containing the list of boxplot.stats.
I now want to reproduce and plot this boxplot from the list. (I have stats, n , conf and out).How should I proceed? Can I use plotly for this purpose?
So I have the following list
stats [1] 0.30518460 0.08578944 0.28487839 0.34645644 0.73711925
n [1] 3472096
conf [1] 0.2846574 0.2850994
out [1] 2.5168701 0.3115725 0.7683801 1.9771345 0.5612497 1.0996948
And my output should be boxplot with the values above.

How to connect leaflet map clicks (events) with plot creation in a shiny app
Hello I am creating an environmental shiny app in which I want to use a leaflet map to create some simple plots. Below I create a sample of my initial data frame:
location = c("100 ail","16th and Whitmore","40AB01  ANTWERPEN") lastUpdated = c("20180201 09:30:00", "20180201 03:00:00", "20170307 10:00:00") firstUpdated = c("20150901 00:00:00","20160306 19:00:00","20161122 15:00:00") pm25=c("FALSE","FALSE","FALSE") pm10=c("TRUE","FALSE","FALSE") no2=c("TRUE","FALSE","FALSE") latitude=c(47.932907,41.322470,36.809700) longitude=c(106.92139000,95.93799000 ,107.65170000) df = data.frame(location, lastUpdated, firstUpdated,latitude,longitude,pm25,pm10,no2)
As a general idea I want to be able to click on a certain location in the map based on this dataframe. Then I have one
selectInput()
and 2dateInput()
. The 2dateInput()
should take as inputs thedf$firstUpdated
anddf$lastUpdated
respectively. Then theselectInput()
should take as inputs the pollutants that exist in thedf
based on "TRUE"/"FALSE" value. And then the plots should be created. All of these should be triggered by clicking on the map.Up to now I was not able to achieve this so in order to help you understand I connected the
selectInput()
and thedateInput()
withinput$loc
which is aselectIpnut()
with locations in the first tab as I will not need this when I find the solution.#ui.r library(shiny) library(leaflet) library(plotly) library(shinythemes) library(htmltools) library(DT) # Define UI for application that draws a histogram navbarPage("ROPENAQ", tabPanel("CREATE DATAFRAME", sidebarLayout( # Sidebar panel for inputs  sidebarPanel( wellPanel( uiOutput("loc"), helpText("Choose a Location to create the dataframe.") ) ), mainPanel( ) ) ), tabPanel("LEAFLET MAP", leafletOutput("map"), wellPanel( uiOutput("dt"), uiOutput("dt2"), helpText("Choose a start and end date for the dataframe creation. Select up to 2 dates") ), "Select your Pollutant", uiOutput("pollutant"), helpText("While all pollutants are listed here, not all pollutants are measured at all locations and all times. Results may not be available; this will be corrected in further revisions of the app. Please refer to the measurement availability in the 'popup' on the map."), hr(), fluidRow(column(8, plotOutput("tim")), column(4,plotOutput("polv"))), hr(), fluidRow(column(4, plotOutput("win")), column(8,plotOutput("cal"))), hr(), fluidRow(column(12, plotOutput("ser")) ) ) ) #server.r # server.R for emission dashboard # load packages library(utilr) library(openair) library(plotly) library(dplyr) library(ggplot2) library(shiny) library(gissr) library(ropenaq) library(worldmet) # load data # veh_data_full < readRDS("veh_data_full.RDS") # veh_data_time_var_type < readRDS("veh_data_time_var_type.RDS") df$location < gsub( " " , "+" , df$location) shinyServer(function(input, output, session) { output$pollutant<renderUI({ selectInput("pollutant", label = h4("Choose Pollutant"), choices = colnames(df[,6:8]), selected = 1) }) #Stores the value of the pollutant selection to pass to openAQ request ################################### #output$OALpollutant < renderUI({OALpollutant}) ################################## # create the map, using dataframe 'locations' which is polled daily (using ropenaq) #MOD TO CONSIDER: addd all available measurements to the popup  true/false for each pollutant, and dates of operation. output$map < renderLeaflet({ leaflet(subset(df,(df[,input$pollutant]=="TRUE")))%>% addTiles() %>% addMarkers(lng = subset(df,(df[,input$pollutant]=="TRUE"))$longitude, lat = subset(df,(df[,input$pollutant]=="TRUE"))$latitude, popup = paste("Location:", subset(df,(df[,input$pollutant]=="TRUE"))$location, "<br>", "Pollutant:", input$pollutant, "<br>", "First Update:", subset(df,(df[,input$pollutant]=="TRUE"))$firstUpdated, "<br>", "Last Update:", subset(df,(df[,input$pollutant]=="TRUE"))$lastUpdated )) }) #Process Tab OAL_site < reactive({ req(input$map_marker_click) location %>% filter(latitude == input$map_marker_click$lat, longitude == input$map_marker_click$lng) ########### #call Functions for data retrieval and processing. Might be best to put all data request #functions into a seperate single function. Need to: # call importNOAA() to retrieve meteorology data into temporary data frame # call aq_measurements() to retrieve air quality into a temporary data frame # merge meteorology and air quality datasets into one working dataset for computations; temporary # meteorology and air quality datasets to be removed. # call openAir() functions to create plots from merged file. Pass output to a dashboard to assemble # into appealing output. # produce output, either as direct download, or as an emailable PDF. # delete all temporary files and reset for next run. }) #fun output$loc<renderUI({ selectInput("loc", label = h4("Choose location"), choices = df$location ,selected = 1 ) }) output$dt<renderUI({ dateInput('date', label = 'First Available Date', value = subset(df$firstUpdated,(df[,1]==input$loc)) ) }) output$dt2<renderUI({ dateInput('date2', label = 'Last available Date', value = subset(df$lastUpdated,(df[,1]==input$loc)) ) }) rt<reactive({ AQ< aq_measurements(location = input$loc, date_from = input$dt,date_to = input$dt2,parameter = input$pollutant) met < importNOAA(year = 2014:2018) colnames(AQ)[9] < "date" merged<merge(AQ, met, by="date") # date output  reports userselected state & stop dates in UI merged$location < gsub( " " , "+" , merged$location) merged }) #DT output$tim = renderPlot({ timeVariation(rt(), pollutant = "value") }) output$polv = renderPlot({ percentileRose(rt(), pollutant = "value", smooth =TRUE) }) output$win = renderPlot({ windRose(rt(),key.footer = "knots") }) output$cal = renderPlot({ calendarPlot(rt(), pollutant = "value") }) output$ser = renderPlot({ timePlot(rt(), pollutant = "value") }) })

How can I grab the row of data from a ggplotly in shiny
Code Below.
I'm trying to use the
plotly_click
event to figure out what data is being selected. However, I can't figure out how to do it. The data provided by plotly_click is very minimal and doesn't include the grouping or groups at all. I don't have any JS experience, but I know there must be a way! My goal is to be able to select a data point and be able to grab the row it corresponds to in a data.framed1
d1=structure(list(Topic = c("compensation", "manager", "benefits", "family", "communication", "worklifebalance", "perks", "compensation", "benefits", "manager", "communication", "worklifebalance", "family", "perks", "benefits", "compensation", "manager", "communication", "family", "worklifebalance", "perks"), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Prct", "Count"), class = "factor"), value = c(2.23121245555964, 0.723305136692411, 0.576192227534633, 0.202280250091946, 0.190020840995464, 0.153242613706019, 0.0122594090964816, 0.913705583756345, 0.609137055837563, 0.50761421319797, 0.50761421319797, 0.304568527918782, 0.203045685279188, 0, 1.49977276170277, 1.21193758521436, 0.893803969095592, 0.439327374640206, 0.348432055749129, 0.242387517042872, 0.0757460990758976), group = c("APAC", "APAC", "APAC", "APAC", "APAC", "APAC", "APAC", "EMEA", "EMEA", "EMEA", "EMEA", "EMEA", "EMEA", "EMEA", "AMERICAS", "AMERICAS", "AMERICAS", "AMERICAS", "AMERICAS", "AMERICAS", "AMERICAS")), .Names = c("Topic", "variable", "value", "group"), class = c("data.table", "data.frame"), row.names = c(NA, 21L)) library(needs) needs( stringr, data.table, tm, ggplot2, wordcloud, readxl, dplyr, quanteda, topicmodels, reshape, plotly, shiny, rCharts, ggthemes, shinyjs, shinyWidgets,DT,shinythemes, ggrepel,tidyverse,treemapify ) options(stringsAsFactors = F) library(shiny) ui < fluidPage( fluidRow(plotlyOutput('keywords')), fluidRow( verbatimTextOutput("selection")) ) server = function(input,output){ output$keywords = renderPlotly({ d0 = d1 p = ggplot(d0, aes(reorder(Topic,value), value)) + geom_point(aes(colour = value), shape = 16, size = 3, show.legend = F) + facet_wrap(~ group)+ theme_minimal() ggplotly(p) }) output$selection < renderPrint({ s < event_data("plotly_click") cat("You selected: \n\n") as.list(s) }) } shinyApp(ui, server)

Shiny is squishing the middle facets in a ggplotly
The middle facet is clearly squished here, but this only happens in shiny. Using just ggplotly() it looks fine.
Code info: d1() is a data.frame that is has 4 columns (Topic, Variable, value, group). I'd like to be able to still use
facet_wrap
and notfacet_grid
because wrap allows you to have different variables on the axis and in some cases, the xaxis(y on plot) will be different in each facet. I've tried adjusting the plotly output with a fixed width and auto width but no dice.dput(d1) structure(list(Topic = c("compensation", "manager", "benefits", "family", "communication", "worklifebalance", "perks", "compensation", "benefits", "manager", "communication", "worklifebalance", "family", "perks", "benefits", "compensation", "manager", "communication", "family", "worklifebalance", "perks"), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Prct", "Count"), class = "factor"), value = c(2.23121245555964, 0.723305136692411, 0.576192227534633, 0.202280250091946, 0.190020840995464, 0.153242613706019, 0.0122594090964816, 0.913705583756345, 0.609137055837563, 0.50761421319797, 0.50761421319797, 0.304568527918782, 0.203045685279188, 0, 1.49977276170277, 1.21193758521436, 0.893803969095592, 0.439327374640206, 0.348432055749129, 0.242387517042872, 0.0757460990758976), group = c("APAC", "APAC", "APAC", "APAC", "APAC", "APAC", "APAC", "EMEA", "EMEA", "EMEA", "EMEA", "EMEA", "EMEA", "EMEA", "AMERICAS", "AMERICAS", "AMERICAS", "AMERICAS", "AMERICAS", "AMERICAS", "AMERICAS")), .Names = c("Topic", "variable", "value", "group"), class = c("data.table", "data.frame" ), row.names = c(NA, 21L), .internal.selfref = <pointer: 0x104803978>) ui = fluidPage( mainPanel( 'Key Words', fluidRow(plotlyOutput('keywords',width = auto)) )) server = function(input,output){ output$keywords = renderPlotly({ d0 = d1 p = ggplot(d0, aes(Topic, value)) + geom_point( aes(colour = value), shape = 16, size = 3, show.legend = F ) + scale_color_gradient(low = "#0091ff", high = "#f0650e") + coord_flip() +facet_wrap(~ group, scales = 'free')+ ylab('Importance Level (Chi2)') + xlab('') + theme_minimal() ggplotly(p) )} }

Plotly for R Fill Between Two X Values
I have plotly code in R that I need to fill between to x values. My code is:
f < list( family = "Times New Roman", size = 18 ) x < list( title = "Time (ms)", titlefont = f ) y < list( title = "PressureCH1 no DC Bias (psi)", titlefont = f ) a < list( x = t_at_peak_p, y = peak_p, text = paste("(", f_t_at_peak_p, ",", f_peak_p,")"), showarrow = TRUE, arrowhead = 9, ax = 20, ay = 40 ) b < list( x = time_start_positive_phase, y = pres_start_positive_phase, text = paste("(", f_t_start_positive_phase, ",", f_p_start_positive_phase,")"), showarrow = TRUE, arrowhead = 9, ax = 30, ay = 50 ) c < list( x = time_end_positive_phase, y = pres_end_positive_phase, text = paste("(", f_t_end_positive_phase, ",", f_p_end_positive_phase,")"), showarrow = TRUE, arrowhead = 9, ax = 30, ay = 50 ) plot_ly(data = shot_data, x = ~Time..ms., y = ~CH1_noDC_psi, type = "scatter", mode = 'lines', fill = 'toself') %>% layout(xaxis = x, yaxis = y) %>% add_markers( x = t_at_peak_p, y = peak_p, showlegend = F, ) %>% layout(annotations = a) %>% add_markers( x = time_start_positive_phase, y = pres_start_positive_phase, showlegend = F, ) %>% layout(annotations = b) %>% add_markers( x = time_start_positive_phase, y = pres_start_positive_phase, showlegend = F, ) %>% layout(annotations = c) %>% add_markers( x = time_end_positive_phase, y = pres_end_positive_phase, showlegend = F, )
I have tried all of the fill combinations tonexty, tonextx, etc. with no luck.
The plotted result is: What I would like is the fill to be limited to 2.566  3.885, i.e. the points shown on the plot. I have been able to produce the plot I want in python and matplotlib:
plt.fill_between(shot_data.index, 0, shot_data[cH],where=(shot_data.index >= pos_phase_t_str) & (shot_data.index <= pos_phase_t_end),alpha=0.3)

Cannot generate different colours using qplot for geom=density
I am trying to generate a density plot using
qplot
for afactor
variable. I used the following codeqplot( file1$month, geom = "density", main ="Density function of Months", xlab = "Month", col=I(("red")))
which works for coloring all the lines but i need different colors for each line i.e. 12 for 12 months. Error says aesthetics must be equal to data which is 4613. I clearly don't have data of 4613. How to plot different colors for each month?

Generating the Intensity distribution of scattered light from a point particle centred on a sphere using python
I am attempting to model a particle in 3 dimensional space which scatters light with an intensity distribution proportional to 1+cos(theta)^2, where theta is measured from the z axis. The particle is point like and so the problem is to calculate an array of points (which will be converted to position vectors acting as the rays of light) which are distributed with a density that follows the 1+cos(theta)^2 distribution.
My first thought was to use an algorithm which evenly distributed points on a sphere and then adjust this to fit the 1+cos(theta)^2 distribution. However the most accurate of these uses random variables to determine the points. Since I want to be able to include an arbitrary number of points I would rather the final method not use random sampling (since a small random sample would yield a poor distribution).
This seems like a very standard problem to me although I have not been able to find anything which directly deals with it.
Here is the code for something I have mashed together (I am not an experienced coder so excuse the poor form):
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np initial_vector = np.array([0,0,1]) def phi_rotation(phi): # rotation matrix about y axis return np.array([[np.cos(phi), 0, np.sin(phi)], [0, 1, 0], [np.sin(phi), 0, np.cos(phi)]]) def theta_rotation(theta): # rotation matrix about x axis (not conventional theta from z axis) return np.array([[1, 0, 0], [0, np.cos(theta), np.sin(theta)], [0, np.sin(theta), np.cos(theta)]]) def generate_equi_intensity(theta, phi_start, phi_end, dphi): """Generates a ring of points for a given angle theta, seperated by an angle dphi from the central axis of rotaion (these should exist in a region of density related to their theta angle by the intensity distribution""" first_vector = theta_rotation(theta).dot(initial_vector) # rotate initial vector into correct theta position vectors = [first_vector] dphi = dphi/(1+np.cos(theta)**2) # angular seperation of vectors is inversely proportional to the intensity distribution for phi in np.linspace(phi_start, phi_enddphi, (phi_endphi_start)/dphi): # rotate vector through phi new_vector = phi_rotation(phi).dot(first_vector) vectors.append(new_vector) return vectors def full_array(theta_start, theta_end, phi_start, phi_end, N): """Generates a ring of points for each theta """ dtheta = (theta_endtheta_start)/N equi_intensitiy_arrays = [] for n, theta in enumerate(np.linspace(theta_start, theta_enddtheta, N)): dphi = dtheta/(np.cos(theta)*(1+np.cos(theta)**2)) # inversely proportional to intensity and cos(theta) vectors = generate_equi_intensity(theta, phi_start, phi_end, dphi) for vector in vectors: # offsets vectors for more even distributiion (doesnt seem to work) vector = phi_rotation(n*1*np.pi/N).dot(vector) equi_intensitiy_arrays.append(vectors) array = np.concatenate(equi_intensitiy_arrays) return array vectors = full_array(np.pi/2, np.pi/2, 0, 2*np.pi, 10) x, y, z = zip(*vectors) print(len(x)) """ ##### PLOTS VECTORS new_vecs=[] for vector in vectors: vector = np.concatenate([[0,0,0], vector]) new_vecs.append(vector) x, y, z, u, v, w = zip(*new_vecs) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.quiver(x, y, z, u, v, w, pivot = "tail") ax.set_xlim([1, 1]) ax.set_ylim([1, 1]) ax.set_zlim([1, 1]) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") plt.show() """ ########## PLOTS DENSITY DISTRIBUTION from scipy import stats xyz = np.vstack([x,y,z]) density = stats.gaussian_kde(xyz)(xyz) idx = density.argsort() x, y ,z = np.array(x), np.array(y) ,np.array(z) x, y, z, density = x[idx], y[idx], z[idx], density[idx] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(x, y, z, c=density) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") fig.colorbar(ax.scatter(x, y, z, c=density)) plt.show()
I have scaled the angular separation of vectors around y axis to scale as 1/cos(theta) as well as 1/(intensity) = 1/(1+cos(theta)^2) this keeps the density of points uniform and stops bunching at the poles.
The problem with the above is that it gives a non homogeneous intensity around the phi angle (this can be seen in the density plot where a line from one pole to the other appears denser that the rest)
Does anyone have a more intuitive way to approach this problem ?
Thankyou.

Yaxis changes with bandwidth in geom_density in R
As far as I understand it, the area under a density curve should always be equal to 1. This does not seem to be the case in R.
My code looks like this:
p < ggplot() + geom_density(data = data_plot, aes_string(x = "value", color = group_by), position = "identity", size = 0.5, na.rm = TRUE) + labs(x = data_plot$unit[data_plot[, group_by] == group_member[1]], y = "density") + scale_colour_manual(values = color) + theme_own() plot(p)
When I change the
geom_density
input intogeom_density(data = data_plot, aes_string(x = "Wert", color = group_by), position = "identity", size = 0.5, na.rm = TRUE, bw = bandwidth)
I get different values on the yaxis.
No manual bw:
Bw = 0.01:
Bw = 0.00001:
Am I interpreting something wrong? I did expect the range of the yaxis to get bigger with a rising bandwith (since many values are at 67 and 100), but shouldn't the curves be lower? For example in the last plot the area is around 30(xaxis)*100(yaxis)=3'000.

R: scatter3D plot with errorbars produces error in plotdev()
I produce 3D scatter plots using R's
plot3D
package. I draw a scatter plot with defined errorbars. Here's a toy examplelibrary("plot3D") aax=c(1,2,3,4,5) aay<c(2,3,4,5,6) aaCI<list(z=matrix(nrow=length(aax),data=c(rep(0,length(aax)),rep(6000,length(aax)) ))) scatter3D(aax,aay,rep(5000,length(aax)),phi = 0, bty = "g", pch = 20, ticktype="detailed",colkey=FALSE,add=FALSE,nticks=3,CI=aaCI, zlim=c(11000,5000))
Everything is OK, but next I want to use the
plotdev()
directive from plot3D package to limit the drawing area and to avoid plotting objects, which are beyond the coordinate data. However, setting any xlim, ylim, zlim limitations produces an error, if scatter3D is invoked with errorbars:plotdev(xlim=c(0,6) ) Error in if (CIpt$dopoints) points(CI.mid$x[io], CI.mid$y[io], col = CIpt$col[io], : argument is of length zero
For all other plots, including scatterplots without error bars, and combination thereof, such subsetting with
plotdev()
works fine. 
Plotting spheres around given coordinates in 3D in Matlab
I am working on model of an object sliding on some rough surface consisting of spheres with a small random variance in position. In the graphics I want the spheres to be of a given radius, however when using scatter3 this wont work, the sizes of the circles change when I zoom in or out. I could easily solve this in 2D by using "rectangle"function instead but for 3D this doesn't work.
Is there a better function for plotting spheres around points?
I have read this https://se.mathworks.com/matlabcentral/answers/101738howdoispecifythesizeofthemarkerscreatedbythescatterplotinunitsproportionaltotheda. But it either doesn't work for scatter3 or I do it wrong.
Sizes change when zooming in.
fig = figure(1); hold on daspect([1,1,1]); surface.xnum = 16; surface.znum = 16; surface.r = 1; circlenumber = 0; for n = 1:surface.xnum for m = 1:surface.znum circlenumber = circlenumber + 1; surface.circlecentre(circlenumber,:) = [n + 0.1*surface.r*randn , 0, m + 0.1*surface.r*randn ]; plt.surface = scatter3(surface.circlecentre(circlenumber, 1),surface.circlecentre(circlenumber, 2),surface.circlecentre(circlenumber, 3), 850*surface.r,'filled','r','MarkerEdgeColor','k'); end end
Relevant part of the code. Setting coordinates to center of the spheres and plotting spheres around them.

How to edit the legend of a scatter plot?
I made a plot with legend. By this code:
scatter3d(x = red, y = green, z = blue, groups = C1class$V1, surface. col = 1:21, grid = FALSE, surface = FALSE) legend3d("right", legend = levels(C1class$V1), col = rainbow(21), pch = 16, inset = 0.25, xpd = TRUE)
But my graph looks like this:
How can I edit it to look better?
Can you help me with some function to fix it?
Thanks for you help.