如何将标签放在饼图之外?

时间:2018-01-10 09:55:34

标签: r ggplot2 pie-chart

如何将标签放在饼图外面以便标签放在适当的位置?

    declare var jQuery: any;

    import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';
    import {Marker} from '../../classes/marker';
    import {LocalStorage, LocalStorageService} from 'ngx-webstorage';

    @Component({
  selector: 'app-overview',
  templateUrl: './overview.component.html'
})
export class OverviewComponent implements OnInit, AfterViewInit {

  markerCombustion: Marker[] = [...];

  @ViewChild('hiddenInput1') hiddenInput1: ElementRef;
  @LocalStorage('frame') public frame: number;
  frameRaw: any;

  constructor(private storage: LocalStorageService) {
  }

  ngOnInit() {
    this.storage.observe('frame')
      .subscribe((newValue) => {
        console.log(newValue);
      });
  }

  ngAfterViewInit() {
      jQuery(this.hiddenInput1.nativeElement).on('change', (e) => {
        this.frameRaw = this.getFrame();
        console.log('test');

        this.frame = this.storage.retrieve('frame');
      });
  }

  getFrame() {

  }

  updateLS() {
    this.storage.store('frame', 20);
  }
}

enter image description here

3 个答案:

答案 0 :(得分:7)

使用:

library(dplyr)
df <- df %>% 
  mutate(end = 2 * pi * cumsum(Value)/sum(Value),
         start = lag(end, default = 0),
         middle = 0.5 * (start + end),
         hjust = ifelse(middle > pi, 1, 0),
         vjust = ifelse(middle < pi/2 | middle > 3 * pi/2, 0, 1))

library(ggforce) # for 'geom_arc_bar'
ggplot(df) + 
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1,
                   start = start, end = end, fill = Product)) +
  geom_text(aes(x = 1.05 * sin(middle), y = 1.05 * cos(middle), label = Label,
                hjust = hjust, vjust = vjust)) +
  coord_fixed() +
  scale_x_continuous(limits = c(-1.5, 1.4),  # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL) +
  scale_y_continuous(limits = c(-1, 1),      # Adjust so labels are not cut off
                     name = "", breaks = NULL, labels = NULL)

给出:

enter image description here

答案 1 :(得分:2)

我试图在@Jaap 的代码中包含产品 1 的标签。我在 geom_text 中更改了 x 和 y 值并且它起作用了。代码中的其他所有内容都相同。

geom_text(aes(x = 1 * sin(middle), y = 1 * cos(middle), label = Label,
            hjust = hjust, vjust = vjust))

答案 2 :(得分:1)

除了@Jaap的解决方案之外,还可以将themescale_y_continuous添加到基本情节p

p <- ggplot(df,aes(x=1,y=Value,fill=Product))+geom_bar(stat="identity", color = "black")

p <- p + coord_polar(theta='y')+ theme(axis.ticks=element_blank(),
                                       axis.text.y=element_blank(),
                                       axis.text.x=element_text(colour='black'),
                                       axis.title=element_blank())
p <- p + scale_y_continuous(breaks=cumsum(df$Value) - df$Value / 2, labels= df$Label)

结果如下: pe-plot