GVKun编程网logo

如何使用pyplot.barh()在每个条形上显示条形的值?(python 条形图)

17

本文的目的是介绍如何在自定义JComponent中使后台工作?的详细情况,特别关注jetpackcompose自定义view的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面

本文的目的是介绍如何在自定义JComponent中使后台工作?的详细情况,特别关注jetpack compose 自定义view的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解如何在自定义JComponent中使后台工作?的机会,同时也不会遗漏关于Angular 2 – 如何在app.component中使用`svg`和将`circle`作为子组件?、Angular 2:如何在该Component中访问自定义Component的FormControl实例?、com.intellij.openapi.components.ComponentConfig的实例源码、C#事件如何在后台工作?的知识。

本文目录一览:

如何在自定义JComponent中使后台工作?(jetpack compose 自定义view)

如何在自定义JComponent中使后台工作?(jetpack compose 自定义view)

在下面的示例中,我JComponent在绿色背景上绘制了一个自定义,但是它没有出现。为什么会这样?

public class Test_Background {    public static class JEllipse extends JComponent {        private final Ellipse2D ellipse;        public JEllipse(int width, int height) {            ellipse = new Ellipse2D.Double(0, 0, width, height);            setOpaque(true);            setBackground(Color.GREEN);        }        @Override        public Dimension getPreferredSize() {            return new Dimension((int) ellipse.getBounds().getMaxX(),                                 (int) ellipse.getBounds().getMaxY());        }        @Override        protected void paintComponent(Graphics g) {            super.paintComponent(g);            ((Graphics2D) g).draw(ellipse);        }    }    public static void main(String[] args) {        SwingUtilities.invokeLater(new Runnable() {            @Override            public void run() {                JEllipse e = new JEllipse(400, 300);                JFrame f = new JFrame("Background Test");                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                f.add(e);                f.pack();                f.setVisible(true);            }        });    }}

答案1

小编典典

JComponent不会绘制其背景。您可以自己绘制,也可以使用可以绘制背景的JPanel

Angular 2 – 如何在app.component中使用`svg`和将`circle`作为子组件?

Angular 2 – 如何在app.component中使用`svg`和将`circle`作为子组件?

所以我想使用Angular开发一个吃豆人游戏,我想使用一个SVG,我想创建一个有嵌入式pacman.component的board.component.

board.component将有一个< svg>< / svg>和pacman.component将有一个< circle>< / circle>但是角度在我的pacman.component中引发了这个错误:

[Angular]’circle’不是已知元素:

  1. If ‘circle‘ is an Angular component,then verify that it is part of this module.
  2. To allow any element add ‘NO_ERRORS_SCHEMA‘ to the ‘@NgModule.schemas‘ of this component.

修复这些错误后,我最终得到了这个SVG:

<svg _ngcontent-c0="" width="100" height="100">
    <app-pacman _ngcontent-c0="" _nghost-c1="">
      <circle _ngcontent-c1="" fill="yellow" r="25" cx="10" cy="10"></circle>
    </app-pacman>
  </svg>

现在唯一的问题是角度包装pacman.component与< app-pacman>< / app-pacman>这使得圈子不起作用.

只是想知道Angular的做法是什么?我不希望在单个组件中包含我的整个svg代码(svg,circle,paths等).

谢谢.

编辑:

board.component.html:

<svg [attr.width]="width" [attr.height]="height">
  <app-pacman></app-pacman>
</svg>

pacman.component.html:

<circle [attr.cx]="cx" [attr.cy]="cy" r="25" fill="yellow"></circle>

解决方法

我相信回答你在这篇精彩文章中描述的问题: https://teropa.info/blog/2016/12/12/graphics-in-angular-2.html#avoiding-element-selectors-for-components

简而言之,您需要将子组件用作属性而不是元素(您可以这样做,因为@Component装饰器派生自@Directive).
适用于您的情况,它看起来像这样:

在board.component.html中:

<svg [attr.width]="width" [attr.height]="height">
    <svg:g app-pacman />
</svg>

在pacman.component.ts中:

@Component({
    selector: '[app-pacman]',templateUrl: ...
})
...

Angular 2:如何在该Component中访问自定义Component的FormControl实例?

Angular 2:如何在该Component中访问自定义Component的FormControl实例?

所以我一直在阅读如何在Angular2中构建自定义FormControls,但我无法得到我正在努力完成验证的工作.我有一个正常的输入控件,我想在自定义组件中包装,以便我可以这样做:

<my-control name="something" [(ngModel)]="model.something" required></my-control>

而不是每次都重复这个:

<divhttps://www.jb51.cc/tag/Feed/" target="_blank">Feedback" [ngClass]="{'has-success': someInput.valid,'has-error': someInput.invalid && someInput.dirty}">
    <labelfor="someId">{{label || 'Some Input'}}</label>
    <input type="test"id="someId" placeholder="Some Input" [ngModel]="value" (ngModel)="onChange($event)" name="someInput" required #someInput="ngModel" minlength="8"/>
    <spanhttps://www.jb51.cc/tag/Feed/" target="_blank">Feedback" aria-hidden="true" [ngClass]="{'glyphicon-ok': someInput.valid,'glyphicon-remove': someInput.invalid && someInput.dirty}"></span>
    <div [hidden]="someInput.valid || someInput.pristine || !someInput.errors.required">Some Input is required</div>
    <div [hidden]="someInput.valid || someInput.pristine || !someInput.errors.minlength">Some Input must be at least 8 characters</div>
</div>

所以我通过自定义组件实现了以下有关如何在线创建自定义组件的文章:

https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

缺少的是能够将验证移出组件,但允许自定义组件处理该验证的显示.因此,如果你看一下我的目的是允许组件的用户指定验证而不是让组件强加特定的验证(注意某些验证是组件固有的,例如电子邮件地址组件会验证它是一封没有用户指定的电子邮件).请注意,必需的是该客户组件的使用情况.

那么如何在该组件的定义中获得对自定义组件的FormControl的引用?注意:我理解如何访问模板的FormControl实例中的输入字段,因为上面的代码完全证明了这一点.我要求的是模板所在的自定义控件的FormControl实例.在我引用的文章中,它将是CounterInputComponent的FormControl.

解决方法

添加这似乎工作:

@ViewChild(NgModel) model: NgModel;

然后你可以通过以下方式访问FormControl:

this.model.control

com.intellij.openapi.components.ComponentConfig的实例源码

com.intellij.openapi.components.ComponentConfig的实例源码

项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
protected final void init(@Nullable ProgressIndicator indicator,@Nullable Runnable componentsRegistered) {
  List<ComponentConfig> componentConfigs = getComponentConfigs();
  for (ComponentConfig config : componentConfigs) {
    registerComponents(config);
  }
  myComponentConfigCount = componentConfigs.size();

  if (componentsRegistered != null) {
    componentsRegistered.run();
  }

  if (indicator != null) {
    indicator.setIndeterminate(false);
  }
  createComponents(indicator);
  myComponentsCreated = true;
}
项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
@NotNull
private List<ComponentConfig> getComponentConfigs() {
  ArrayList<ComponentConfig> componentConfigs = new ArrayList<ComponentConfig>();
  boolean isDefaultProject = this instanceof Project && ((Project)this).isDefault();
  boolean headless = ApplicationManager.getApplication().isHeadlessEnvironment();
  for (IdeaPluginDescriptor plugin : PluginManagerCore.getPlugins()) {
    if (PluginManagerCore.shouldSkipPlugin(plugin)) {
      continue;
    }

    ComponentConfig[] configs = getMyComponentConfigsFromDescriptor(plugin);
    componentConfigs.ensureCapacity(componentConfigs.size() + configs.length);
    for (ComponentConfig config : configs) {
      if ((!isDefaultProject || config.isLoadForDefaultProject()) && isComponentSuitable(config.options) && config.prepareClasses(headless)) {
        config.pluginDescriptor = plugin;
        componentConfigs.add(config);
      }
    }
  }
  return componentConfigs;
}
项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
private void registerComponents(@NotNull ComponentConfig config) {
  ClassLoader loader = config.getClassLoader();
  try {
    final Class<?> interfaceClass = Class.forName(config.getInterfaceClass(),true,loader);
    final Class<?> implementationClass = Comparing.equal(config.getInterfaceClass(),config.getImplementationClass())
                                         ?
                                         interfaceClass
                                         : StringUtil.isEmpty(config.getImplementationClass()) ? null : Class.forName(config.getImplementationClass(),loader);
    Mutablepicocontainer picocontainer = getpicocontainer();
    if (config.options != null && Boolean.parseBoolean(config.options.get("overrides"))) {
      ComponentAdapter oldAdapter = picocontainer.getComponentAdapterOfType(interfaceClass);
      if (oldAdapter == null) {
        throw new RuntimeException(config + " does not override anything");
      }
      picocontainer.unregisterComponent(oldAdapter.getComponentKey());
    }
    // implementationClass == null means we want to unregister this component
    if (implementationClass != null) {
      picocontainer.registerComponent(new ComponentConfigComponentAdapter(interfaceClass,implementationClass,config.getPluginId(),config.options != null && Boolean.parseBoolean(config.options.get("workspace"))));
    }
  }
  catch (Throwable t) {
    handleInitComponentError(t,null,config.getPluginId());
  }
}
项目:tools-idea    文件:PluginManager.java   
public static void handleComponentError(Throwable t,String componentClassName,ComponentConfig config) {
  if (t instanceof StartupAbortedException) {
    throw (StartupAbortedException)t;
  }

  PluginId pluginId = config != null ? config.getPluginId() : getPluginByClassName(componentClassName);

  if (pluginId != null && !CORE_PLUGIN_ID.equals(pluginId.getIdString())) {
    getLogger().warn(t);

    disablePlugin(pluginId.getIdString());

    String message =
      "Plugin '" + pluginId.getIdString() + "' Failed to initialize and will be disabled\n" +
      "(reason: " + t.getMessage() + ")\n\n" +
      ApplicationNamesInfo.getInstance().getFullProductName() + " will be restarted.";
    Main.showMessage("Plugin Error",message,false);

    throw new StartupAbortedException(t).exitCode(Main.PLUGIN_ERROR).logError(false);
  }
  else {
    throw new StartupAbortedException("Fatal error initializing '" + componentClassName + "'",t);
  }
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptorImpl.java   
private static ComponentConfig[] mergeComponents(ComponentConfig[] first,ComponentConfig[] second) {
  if (first == null) {
    return second;
  }
  if (second == null) {
    return first;
  }
  return ArrayUtil.mergeArrays(first,second);
}
项目:tools-idea    文件:ApplicationImpl.java   
@Override
protected void handleInitComponentError(Throwable t,ComponentConfig config) {
  if (!myHandlingInitComponentError) {
    myHandlingInitComponentError = true;
    try {
      PluginManager.handleComponentError(t,componentClassName,config);
    }
    finally {
      myHandlingInitComponentError = false;
    }
  }
}
项目:tools-idea    文件:ComponentManagerConfigurator.java   
public void loadComponentsConfiguration(final ComponentConfig[] components,final PluginDescriptor descriptor,final boolean defaultProject) {
  if (components == null) return;

  loadConfiguration(components,defaultProject,descriptor);
}
项目:tools-idea    文件:IdeaPluginDescriptorImpl.java   
private static ComponentConfig[] mergeComponents(ComponentConfig[] first,second);
}
项目:consulo    文件:PlatformComponentManagerImpl.java   
@Override
protected void handleInitComponentError(@Nonnull Throwable ex,@Nullable String componentClassName,@Nullable ComponentConfig config) {
  if (!myHandlingInitComponentError) {
    myHandlingInitComponentError = true;
    try {
      PluginManager.handleComponentError(ex,config);
    }
    finally {
      myHandlingInitComponentError = false;
    }
  }
}
项目:consulo    文件:PluginManager.java   
public static void handleComponentError(@Nonnull Throwable t,@Nullable ComponentConfig config) {
  if (t instanceof StartupAbortedException) {
    throw (StartupAbortedException)t;
  }

  PluginId pluginId = null;
  if (config != null) {
    pluginId = config.getPluginId();
  }
  if (pluginId == null || CORE_PLUGIN.equals(pluginId)) {
    pluginId = componentClassName == null ? null : getPluginByClassName(componentClassName);
  }
  if (pluginId == null || CORE_PLUGIN.equals(pluginId)) {
    if (t instanceof PicopluginExtensionInitializationException) {
      pluginId = ((PicopluginExtensionInitializationException)t).getPluginId();
    }
  }

  if (pluginId != null && !isSystemPlugin(pluginId)) {
    getLogger().warn(t);

    if(!ApplicationProperties.isInSandBox()) {
      disablePlugin(pluginId.getIdString());
    }

    StringWriter message = new StringWriter();
    message.append("Plugin '").append(pluginId.getIdString()).append("' Failed to initialize and will be disabled. ");
    message.append(" Please restart ").append(ApplicationNamesInfo.getInstance().getFullProductName()).append('.');
    message.append("\n\n");
    t.printstacktrace(new PrintWriter(message));
    Main.showMessage("Plugin Error",message.toString(),t);
  }
}
项目:consulo    文件:ComponentManagerConfigurator.java   
public void loadComponentsConfiguration(final ComponentConfig[] components,descriptor);
}
项目:consulo    文件:IdeaPluginDescriptorImpl.java   
private static ComponentConfig[] mergeComponents(ComponentConfig[] first,second);
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getAppComponents();
项目:intellij-ce-playground    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getProjectComponents();
项目:intellij-ce-playground    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getModuleComponents();
项目:intellij-ce-playground    文件:ApplicationImpl.java   
@NotNull
@Override
public ComponentConfig[] getMyComponentConfigsFromDescriptor(@NotNull IdeaPluginDescriptor plugin) {
  return plugin.getAppComponents();
}
项目:intellij-ce-playground    文件:DummyProject.java   
@NotNull
public ComponentConfig[] getComponentConfigurations() {
  return new ComponentConfig[0];
}
项目:intellij-ce-playground    文件:DummyProject.java   
@Nullable
public Object getComponent(final ComponentConfig componentConfig) {
  return null;
}
项目:intellij-ce-playground    文件:DummyProject.java   
public ComponentConfig getConfig(Class componentImplementation) {
  throw new UnsupportedOperationException("Method getConfig not implemented in " + getClass());
}
项目:intellij-ce-playground    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getAppComponents() {
  throw new IllegalStateException();
}
项目:intellij-ce-playground    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getProjectComponents() {
  throw new IllegalStateException();
}
项目:intellij-ce-playground    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getModuleComponents() {
  throw new IllegalStateException();
}
项目:intellij-ce-playground    文件:ComponentManagerImpl.java   
@NotNull
public ComponentConfig[] getMyComponentConfigsFromDescriptor(@NotNull IdeaPluginDescriptor plugin) {
  return plugin.getAppComponents();
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getAppComponents() {
  return myAppComponents;
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getProjectComponents() {
  return myProjectComponents;
}
项目:intellij-ce-playground    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getModuleComponents() {
  return myModuleComponents;
}
项目:tools-idea    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getAppComponents();
项目:tools-idea    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getProjectComponents();
项目:tools-idea    文件:IdeaPluginDescriptor.java   
@NotNull
ComponentConfig[] getModuleComponents();
项目:tools-idea    文件:DummyProject.java   
@NotNull
public ComponentConfig[] getComponentConfigurations() {
  return new ComponentConfig[0];
}
项目:tools-idea    文件:DummyProject.java   
@Nullable
public Object getComponent(final ComponentConfig componentConfig) {
  return null;
}
项目:tools-idea    文件:DummyProject.java   
public ComponentConfig getConfig(Class componentImplementation) {
  throw new UnsupportedOperationException("Method getConfig not implemented in " + getClass());
}
项目:tools-idea    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getAppComponents() {
  throw new IllegalStateException();
}
项目:tools-idea    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getProjectComponents() {
  throw new IllegalStateException();
}
项目:tools-idea    文件:PluginNode.java   
@NotNull
public ComponentConfig[] getModuleComponents() {
  throw new IllegalStateException();
}
项目:tools-idea    文件:ComponentManagerConfigurator.java   
private void loadConfiguration(final ComponentConfig[] configs,final boolean defaultProject,final PluginDescriptor descriptor) {
  for (ComponentConfig config : configs) {
    loadSingleConfig(defaultProject,config,descriptor);
  }
}
项目:tools-idea    文件:ComponentManagerConfigurator.java   
private void loadSingleConfig(final boolean defaultProject,final ComponentConfig config,final PluginDescriptor descriptor) {
  if (defaultProject && !config.isLoadForDefaultProject()) return;
  if (!myComponentManager.isComponentSuitable(config.options)) return;

  myComponentManager.registerComponent(config,descriptor);
}
项目:tools-idea    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getAppComponents() {
  return myAppComponents;
}
项目:tools-idea    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getProjectComponents() {
  return myProjectComponents;
}
项目:tools-idea    文件:IdeaPluginDescriptorImpl.java   
@Override
@NotNull
public ComponentConfig[] getModuleComponents() {
  return myModuleComponents;
}

C#事件如何在后台工作?

C#事件如何在后台工作?

我正在使用C#、. NET 3.5。我了解如何利用事件,如何在类中声明事件,如何将它们与其他地方挂钩等等。一个人为的示例:

public class MyList{    private List<string> m_Strings = new List<string>();    public EventHandler<EventArgs> ElementAddedEvent;    public void Add(string value)    {        m_Strings.Add(value);        if (ElementAddedEvent != null)            ElementAddedEvent(value, EventArgs.Empty);    }}[TestClass]public class TestMyList{    private bool m_Fired = false;    [TestMethod]    public void TestEvents()    {        MyList tmp = new MyList();        tmp.ElementAddedEvent += new EventHandler<EventArgs>(Fired);        tmp.Add("test");        Assert.IsTrue(m_Fired);    }    private void Fired(object sender, EventArgs args)    {        m_Fired = true;    }}

但是,我 明白的是,当有人声明一个事件处理程序时

public EventHandler<EventArgs> ElementAddedEvent;

它从未被初始化-那么,ElementAddedEvent到底是什么?它指向什么?以下内容将不起作用,因为EventHandler从未初始化:

[TestClass]public class TestMyList{    private bool m_Fired = false;    [TestMethod]    public void TestEvents()    {        EventHandler<EventArgs> somethingHappend;        somethingHappend += new EventHandler<EventArgs>(Fired);        somethingHappend(this, EventArgs.Empty);        Assert.IsTrue(m_Fired);    }    private void Fired(object sender, EventArgs args)    {        m_Fired = true;    }}

我注意到有一个EventHandler.CreateDelegate(…),但是所有方法签名都表明这仅用于通过典型的ElementAddedEvent
+ = new EventHandler(MyMethod)将Delegates附加到已经存在的EventHandler。

我不知道 是什么
,我试图做将帮助......但最终我想拿出在LINQ一个抽象父的DataContext他们的孩子可以注册自己想要的表类型“观察”这样我就可以有事件例如BeforeUpdate和AfterUpdate,但特定于类型。像这样:

public class BaseDataContext : DataContext{    private static Dictionary<Type, Dictionary<ChangeAction, EventHandler>> m_ObservedTypes = new Dictionary<Type, Dictionary<ChangeAction, EventHandler>>();    public static void Observe(Type type)    {        if (m_ObservedTypes.ContainsKey(type) == false)        {            m_ObservedTypes.Add(type, new Dictionary<ChangeAction, EventHandler>());            EventHandler eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;            m_ObservedTypes[type].Add(ChangeAction.Insert, eventHandler);            eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;            m_ObservedTypes[type].Add(ChangeAction.Update, eventHandler);            eventHandler = EventHandler.CreateDelegate(typeof(EventHandler), null, null) as EventHandler;            m_ObservedTypes[type].Add(ChangeAction.Delete, eventHandler);        }    }    public static Dictionary<Type, Dictionary<ChangeAction, EventHandler>> Events    {        get { return m_ObservedTypes; }    }}public class MyClass{    public MyClass()    {        BaseDataContext.Events[typeof(User)][ChangeAction.Update] += new EventHandler(OnUserUpdate);    }    public void OnUserUpdated(object sender, EventArgs args)    {        // do something    }}

考虑到这一点,使我意识到我不太了解事件发生后的状况-我想理解:)

答案1

小编典典

我已经在文章中详细介绍了这一点,但是这里是总结,假设您对委托人自己很满意:

  • 事件实际上是“添加”方法和“删除”方法,就像属性实际上只是“获取”方法和“设置”方法一样。(实际上,CLI也允许使用“ raise / fire”方法,但是C#从未生成此方法。)元数据通过引用方法来描述事件。
  • 当您声明类似 字段的事件 (例如ElementAddedEvent)时,编译器将生成方法 和私有字段 (与委托的类型相同)。在类中,当您引用ElementAddedEvent时,您是在引用字段。在课堂之外,您指的是领域。
  • 任何人订阅使用add方法的事件(使用+ =运算符)时。当他们退订(使用-=运算符)时,将调用remove。
  • 对于类似字段的事件,需要进行一些同步,否则添加/删除仅调用Delegate。合并 / 删除以更改自动生成的字段的值。这两个操作都分配给后备字段-请记住,委托是不可变的。换句话说,自动生成的代码非常像这样:

    // Backing field

    // The underscores just make it simpler to see what’s going on here.
    // In the rest of your source code for this class, if you refer to
    // ElementAddedEvent, you’re really referring to this field.
    private EventHandler __ElementAddedEvent;

    // Actual event
    public EventHandler ElementAddedEvent
    {
    add
    {
    lock(this)
    {
    // Equivalent to __ElementAddedEvent += value;
    __ElementAddedEvent = Delegate.Combine(__ElementAddedEvent, value);
    }
    }
    remove
    {
    lock(this)
    {
    // Equivalent to __ElementAddedEvent -= value;
    __ElementAddedEvent = Delegate.Remove(__ElementAddedEvent, value);
    }
    }
    }

  • 在您的情况下,所生成字段的初始值为null-,并且null如果所有订阅者都被删除,它将始终再次变为初始值,这就是Delegate.Remove的行为。

  • 如果您希望“无操作”处理程序订阅您的事件,以避免无效检查,则可以执行以下操作:

    public EventHandler<EventArgs> ElementAddedEvent = delegate {};

delegate {}只是它不关心它的参数,所以没有任何一个匿名方法。

如果还有什么不清楚的地方,请询问,我将尽力帮助!

关于如何在自定义JComponent中使后台工作?jetpack compose 自定义view的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Angular 2 – 如何在app.component中使用`svg`和将`circle`作为子组件?、Angular 2:如何在该Component中访问自定义Component的FormControl实例?、com.intellij.openapi.components.ComponentConfig的实例源码、C#事件如何在后台工作?的相关信息,请在本站寻找。

在本文中,我们将带你了解如何使用pyplot.barh在这篇文章中,我们将为您详细介绍如何使用pyplot.barh的方方面面,并解答在每个条形上显示条形的值?常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的ggplot2 中的条形图显示每个条形和 c、ggplot不显示条形图中的颜色、jquery – 使用c3js更改条形图中单个条形的颜色、MatPlotLib:如何为堆叠的条形图在每个条形上显示总和标签?

本文目录一览:

如何使用pyplot.barh()在每个条形上显示条形的值?(python 条形图)

如何使用pyplot.barh()在每个条形上显示条形的值?(python 条形图)

我生成了条形图,如何在每个条形上显示条形的值?

我的代码:

import osimport numpy as npimport matplotlib.pyplot as pltx = [u''INFO'', u''CUISINE'', u''TYPE_OF_PLACE'', u''DRINK'', u''PLACE'', u''MEAL_TIME'', u''DISH'', u''NEIGHBOURHOOD'']y = [160, 167, 137, 18, 120, 36, 155, 130]fig, ax = plt.subplots()    width = 0.75 # the width of the bars ind = np.arange(len(y))  # the x locations for the groupsax.barh(ind, y, width, color="blue")ax.set_yticks(ind+width/2)ax.set_yticklabels(x, minor=False)plt.title(''title'')plt.xlabel(''x'')plt.ylabel(''y'')      #plt.show()plt.savefig(os.path.join(''test.png''), dpi=300, format=''png'', bbox_inches=''tight'') # use format=''svg'' or ''pdf'' for vectorial pictures

答案1

小编典典

加:

for i, v in enumerate(y):    ax.text(v + 3, i + .25, str(v), color=''blue'', fontweight=''bold'')

结果:

yv既是x位置,也是的字符串值ax.text,方便地,条形图的每个条形的度量均为1,因此枚举iy位置。

ggplot2 中的条形图显示每个条形和 c

ggplot2 中的条形图显示每个条形和 c

如何解决ggplot2 中的条形图显示每个条形和 c?

我有这样的数据:

SupplyChain Value
 A     1000
 B     2000
 C     3000

我想制作一个条形图,将 x 轴作为“供应链”,将 y 轴作为值,但是,在图表中,每个条形内都有一个总数的百分比。例如,在柱状图 A 的图表中,柱状图顶部的值将是“1000”的 16.67%

此外,我也想为每个供应链分配一组颜色,我尝试在 ggplot 中使用“scale_colour_manual”,但我没有运气。这是我想要的示例:

enter image description here

解决方法

这是一种方法-

library(dplyr)
library(ggplot2)

df %>%
  mutate(Percentage = paste(round(prop.table(Value) * 100,2),''%'')) %>%
  ggplot(aes(SupplyChain,Value)) + 
  geom_col() + 
  geom_text(aes(label = Percentage),vjust = -0.5)

enter image description here

ggplot不显示条形图中的颜色

ggplot不显示条形图中的颜色

填充颜色符合美学要求

ggplot(top5_energyProducersMod,aes(year,ggwt_hours,fill = year)) +
  geom_bar(stat = "identity",position = "dodge") +
  facet_wrap(~country_name)

jquery – 使用c3js更改条形图中单个条形的颜色

jquery – 使用c3js更改条形图中单个条形的颜色

如何更改条形图中单个条形的颜色.

var chart = c3.generate({
    data: {
        columns: [
            ['data1',30,20,50,40,60,50]

        ],type: 'bar',colors: {
            data1: '#ff0000'
        },color: function (color,d) {

            return d.id && d.id === 'data1' ? d3.rgb(color).darker(d.value / 120) : color;
        }
    }
});

这里,所有值大于45的条形应为绿色,45以下的条形应为红色.

解决方法

只需将data.colors.data1作为一个函数,就像这样

var chart = c3.generate({
    data: {
        columns: [
            ['data1',colors: {
            data1: function(d) {
                return (d.value >= 45) ? '#00ff00': '#ff0000';
            }
        }
    },legend: {
       show: false
    },// take care of color in tooltip
    tooltip: {
        contents: function (d,defaultTitleFormat,defaultValueFormat,color) {
            color = function() {
                return (d[0].value >= 45) ? '#00ff00' : '#ff0000';
            };
            return chart.internal.getTooltipContent.call(this,d,color)
        }
    }
});

顺便说一句,我认为45是绿色的.

小提琴 – http://jsfiddle.net/vc1Lq1um/

MatPlotLib:如何为堆叠的条形图在每个条形上显示总和标签?

MatPlotLib:如何为堆叠的条形图在每个条形上显示总和标签?

更新:弄清楚了,我只需要手工总结一下,然后使用plt.text。在上一个单元格中,我已将months初始化为月份名称的列表。

解决方案:

monthTotals = []
for month in months:
    total = 0
    total += int(okrs_results[okrs_results['Month'] == month]['Page Views'])
    total += int(blog_results[blog_results['Month'] == month]['Page Views'])
    total += int(landing_page_results[landing_page_results['Month'] == month]['Page Views'])
    total += int(teams_results[teams_results['Month'] == month]['Page Views'])
    total += int(events_results[events_results['Month'] == month]['Page Views'])
    total += int(initiatives_results[initiatives_results['Month'] == month]['Page Views'])
    total += int(tools_results[initiatives_results['Month'] == month]['Page Views'])
    monthTotals.append(total)

okrViews = okrs_results['Page Views'].tolist()
blogViews = blog_results['Page Views'].tolist()
landingPageViews = landing_page_results['Page Views'].tolist()
teamsViews = teams_results['Page Views'].tolist()
eventsViews = events_results['Page Views'].tolist()
initiativesViews = initiatives_results['Page Views'].tolist()
toolsViews = tools_results['Page Views'].tolist()
indx = np.arange(len(months))

# Calculate starting position for each bar
okrsAndBlogs = [i+j for i,j in zip(okrViews,blogViews)]
okrsBlogsLanding = [i+j for i,j in zip(landingPageViews,okrsAndBlogs)]
four = [i+j for i,j in zip(teamsViews,okrsBlogsLanding)]
five = [i+j for i,j in zip(eventsViews,four)]
six = [i+j for i,j in zip(initiativesViews,five)]

# Set figure size
plt.figure(figsize=(19,10))

# Add each bar
graphBlogs = plt.bar(x = indx,height = blogViews,width = .45,color='tab:blue',label = 'Blogs')
graphOkrs = plt.bar(x = indx,height = okrViews,color='tab:pink',bottom = blogViews,label = 'OKRs')
graphLanding = plt.bar(x = indx,height = landingPageViews,color='green',bottom = okrsAndBlogs,label = 'Landing Page')
graphTeams = plt.bar(x = indx,height = teamsViews,color='orange',bottom = okrsBlogsLanding,label = 'Teams')
graphEvents = plt.bar(x = indx,height = eventsViews,color='tab:olive',bottom = four,label = 'Events')
graphInitiatives = plt.bar(x = indx,height = initiativesViews,color='tab:purple',bottom = five,label = 'Initiatives; Risk and Data Privacy')
graphTools = plt.bar(x = indx,height = toolsViews,color='tab:cyan',bottom = six,label = 'Tools')

# Show sum on each stacked bar
for i,v in enumerate(monthTotals):
    if v != 0:
        plt.text(indx[i] - .2,v,str(v))
    
# Set labels
plt.xticks(indx,months)
plt.xlabel("Month")
plt.ylabel("Total Views")
plt.title('Views per Day,Grouped by Month,YTD')
plt.legend()

plt.show()

结果:

Solution

今天关于如何使用pyplot.barh在每个条形上显示条形的值?的分享就到这里,希望大家有所收获,若想了解更多关于ggplot2 中的条形图显示每个条形和 c、ggplot不显示条形图中的颜色、jquery – 使用c3js更改条形图中单个条形的颜色、MatPlotLib:如何为堆叠的条形图在每个条形上显示总和标签?等相关知识,可以在本站进行查询。

本文标签: