Asked  7 Months ago    Answers:  5   Viewed   24 times

Let's assume I have 2 source files, the first one named example1.r and the second one example2.r (given below).





When I source example1.r, the graph is drawn. It does not, however, when I source example2.r. What is the solution here?

(qplot in example2.r is ggplot2's function)




  • .R files: source's option print.eval=TRUE will lead to printing behaviour of the evaluation result like in the interactive command line.

source("Script.R", print.eval=TRUE)

  • .Rnw files: knitr by default emulates the behaviour of the interactive command line wrt. printing. Note that knitr can be specified as Sweaving engine also for R package vignettes.

This is my original answer. But note that this workaround is IMHO completely obsolete now (and it always was good for a small lazy niche only).

This is the famous FAQ 7.22: Why do lattice/trellis graphics not work?.

For grid graphics like ggplot2 or lattice, you need to print the graphics object in order to actually draw it.

Interactively on the command line this is done automatically. Everywhere else (inside files to be sourced, loops, functions, Sweave chunks) you need to print it explicitly.

print (qplot (1 : 10, 1 : 10))

Alternatively, you can redefine qplot to do the printing:

qplot <- function (x, y = NULL, z = NULL, ...) {
  p <- ggplot2::qplot (x = x, y = y, z = z, ...)
  print (p)

(this changes the axis labels to x and y).

I use this approach in vignettes where I want to write code exactly as a user in an interactive session would type it.

Tuesday, June 1, 2021
answered 7 Months ago

The key with ordering is to set the levels of the factor in the order you want. An ordered factor is not required; the extra information in an ordered factor isn't necessary and if these data are being used in any statistical model, the wrong parametrisation might result — polynomial contrasts aren't right for nominal data such as this.

## set the levels in order we want
theTable <- within(theTable, 
                   Position <- factor(Position, 
## plot

barplot figure

In the most general sense, we simply need to set the factor levels to be in the desired order. If left unspecified, the levels of a factor will be sorted alphabetically. You can also specify the level order within the call to factor as above, and other ways are possible as well.

theTable$Position <- factor(theTable$Position, levels = c(...))
Tuesday, June 1, 2021
answered 7 Months ago

If do you have already permissions then:

In your service class or another service/activity you can switch the "component hability" to listen notifications:

    public void tryReconnectService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            ComponentName componentName =
                    new ComponentName(getApplicationContext(), NotificationReaderV2Service.class);

            //It say to Notification Manager RE-BIND your service to listen notifications again inmediatelly!

* Try deactivate/activate your component service
    private void toggleNotificationListenerService() {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(this, NotificationReaderV2Service.class),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(new ComponentName(this, NotificationReaderV2Service.class),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

Your notification listener, is a SERVICE, it can be killed by System, you can do your service as FOREGROUND to drastically decrease the probability that the system will kill your service.

    public void onListenerConnected() {
        Log.d(TAG, "Service Reader Connected");
    Notification not = createNotification();
    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (mNotificationManager != null) {
        mNotificationManager.notify(NOTIFICATION_ID, not);

    startForeground(NOTIFICATION_ID, not);

    //Alarm to auto - send Intents to Service to reconnect, you can ommit next line.

If do you like so more "safe", you can to programming not-friendly battery alarms, try to use inexact alarms please, the user's battery will be happy:

private void alarmIt() {
    Log.d(TAG, "ALARM PROGRAMMATED at"+HotUtils.formatDate(new Date()));
    Calendar now = Calendar.getInstance();
    now.set(Calendar.MINUTE, now.get(Calendar.MINUTE) + 1);

    Intent intent = new Intent(this, NotificationReaderV2Service.class);

    PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            intent, 0);

    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //The alarms that are repeated are inaccurate by default, use RTC_WAKE_UP at your convenience.
    //Alarm will fire every minute, CHANGE THIS iF DO YOU CAN, you can't use less than 1 minute to repeating alarms.
    manager.setRepeating(AlarmManager.RTC_WAKEUP, now.getTimeInMillis(), 1000 * 60 * 1, pendingIntent);

and next read the Intent to reconnect service binding:

public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Notification service onStartCommandCalled");
    if (intent!=null && !HotUtils.isNullOrEmpty(intent.getAction()) && intent.getAction().equals(REBIND_ACTION)){
        Log.d(TAG, "TRYING REBIND SERVICE at "+HotUtils.formatDate(new Date()));
        tryReconnectService();//switch on/off component and rebind
    //START_STICKY  to order the system to restart your service as soon as possible when it was killed.
    return START_STICKY;

Keep in mind that doing all these steps you can sure that your service will be killed anyway by the system but this code will restart the service and make it harder to kill it.

Maybe, you should consider using PARTIAL_WAKE_LOCK with your service and execute it in a process independently (:remote) if you want even more certainty (Maybe this is useless)

I would like to add a common error that is often followed, NEVER override the onBind and onUnbind method or overwrite the INTENT ACTION. This will cause your service to not be connected and never run onListenerConnected Keep the Intent as it is, in most cases you do not need to edit it.

Wednesday, August 4, 2021
answered 4 Months ago

With notepad++ you'll need to use 2-1 as the replacement string.

Sources :
Mark's Speechblog

Thursday, September 9, 2021
answered 3 Months ago

If you reverse the order of the to tile layers, it works.


p <- ggplot(agg, aes(Year, WeekOfMonth, fill = NumericField))
noData <- subset(agg,$NumericField))
p <- p + geom_tile(data = subset(agg, !$NumericField)), aes(fill = NumericField), color = "gray")
if(nrow(noData) > 0) p <- p + geom_tile(data = noData, color = "gray", fill = "white")


p <- ggplot(agg,aes(Year, WeekOfMonth, fill = NumericField))  
noData <- subset(agg,$NumericField)) 
if(nrow(noData) > 0) p <- p + geom_tile(data = noData, color = "gray", fill = "white")
p <- p + geom_tile(data = subset(agg, !$NumericField)), aes(fill = NumericField), color = "gray")

I think the problem is to do with ggplot's treatment of factors,e.g., agg$WeekOfMonth, that have missing levels. One way around this is to avoid making agg$WeekOfMonth a factor.

agg$WeekOfMonth <- 1 + week.of.month(agg$Year, agg$MonthNumber, agg$Day)
p <- ggplot(agg)
p <- p + aes(Year, -WeekOfMonth, fill = NumericField)  
noData <- subset(agg,$NumericField))
p <- p + geom_tile(data = subset(agg, !$NumericField)), aes(fill = NumericField), color = "gray")
if(nrow(noData) > 0)p <- p + geom_tile(data = noData, color = "gray", fill = "white")

To avoid negative y-axis labels, you have to add:

p <- p + scale_y_continuous(label=abs)

to the ggplot layer definitions. This produces the same plot as above, and does not require reversing the order of the tile layers.

EDIT Found a much better way to do this.

By using the na.value-... argument to scale_fill_continuous(...) you can avoid multiple datasets completely.

p <- ggplot(agg)
p <- p + aes(Year, WeekOfMonth, fill = NumericField)
p <- p + geom_tile(aes(fill = NumericField), color = "gray")
p <- p + scale_fill_gradient(low = lowColor, high = highColor, na.value="white")

This avoids the need for noData altogether.

Finally, I suppose you have a reason for displaying the calendars this way, but IMO here is a more intuitive calendar view.

gg.calendar <- function(df) {
  wom <- function(date) { # week-of-month
    first <- wday(as.Date(paste(year(date),month(date),1,sep="-")))
    return((mday(date)+(first-2)) %/% 7+1)
  df$month <- month(df$dates)
  df$day   <- mday(df$dates)

  rng   <- range(df$dates)
  rng   <- as.Date(paste(year(rng),month(rng),1,sep="-"))
  start <- rng[1]
  end   <- rng[2]
  month(end) <- month(end)+1
  day(end)   <- day(end)  -1

  cal <- data.frame(dates=seq(start,end,by="day"))
  cal$year  <- year(cal$dates)
  cal$month <- month(cal$dates)
  cal$cmonth<- month(cal$dates,label=T)
  cal$day   <- mday(cal$dates)
  cal$cdow  <- wday(cal$dates,label=T)
  cal$dow   <- wday(cal$dates)
  cal$week  <- wom(cal$dates)

  cal        <- merge(cal,df[,c("dates","counts")],all.x=T)

  ggplot(cal, aes(x=cdow,y=-week))+
    facet_wrap(~cmonth, ncol=3)+
    scale_fill_gradient(low = "moccasin", high = "dodgerblue", na.value="white")+
Friday, December 3, 2021
answered 4 Days ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :