R:3d看单维画面

时间:2015-10-30 17:38:54

标签: python r plot bar-chart

我尝试使用包epade,但我失败了!

实施例: x值中的每一个都定义了每个条形的高度(存在多个x值的条形,高度为x

xa<-c(9.45,6.79,14.03,7.25,16.16,19.42,16.30,4.60,14.76,19.24,
  16.04,7.80,13.16,10.00,15.76,16.29,19.52,27.22,7.74,6.75)
barplot(xa)

所以我想在3d看时尚中完全相同的情节! 有可能吗?

更新 解决方案 这是在Python中完成的,而不是在R:(

以下是代码:

# needed modules
import csv
import pandas as pandas
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.interpolate import spline
from textwrap import wrap
from mpl_toolkits.mplot3d import proj3d
import pylab
import os

# we define some names in order to change only one
# 3 columnes are imported each time
# by changing col_inc from 0 to something
# we can define which range of columns will be imported
col_num = np.arange(2, 1001)
col_num_tuple = tuple(col_num)
cnt = col_num_tuple
cnt

# last counter col_inc = 279
col_inc = 273
str = 0 + col_inc
fin = 3 + col_inc
cols = cnt[str:fin]
cols

# importing a simple datafile, csv type. Data are comma seperated
# importing only 1st, 2nd and 4th columns
# We can call these data now by giving a new name, 'io'.

io = pandas.read_csv(
    '/data.csv', sep=",", usecols=cols)

# Try to get the name of singer & the name of song
# in the first two rows
names = io[0:2]
nm = names
nm1 = np.array(nm[:], dtype='string')
nm_singer = nm1[0:1][0:2, 1][0]
nm_song = nm1[1:2][0:2, 1][0]
nm_singer
nm_song
nms = nm_singer + ' - ' + nm_song

# we drop nan values
io = io.dropna()

# we make this in order not change each time, the name of column
io_all = np.array(io[3:])
io_st = np.array(io_all[:, 0], dtype=float)
io_end = np.array(io_all[:, 1], dtype=float)
io_dur = np.array(io_all[:, 2], dtype=float)
io_all
io_st
io_end
io_dur

# We define a new name for the column that is named alice inside io dataset
result = io_dur
# we need to make these data 'array type'
result = np.array(result)

# we now define the dimensions of our figure/plot, as well its dpi
fig = plt.figure(figsize=(16, 8), dpi=150)

# This line defines our first plot
# Afterwards, the '112' will define our second plot.
ax1 = fig.add_subplot(111, projection='3d')
# ax1 = Axes3D(fig)

# we define here labels
xlabels = io_end
xpos = np.arange(xlabels.shape[0])
ylabels = np.array([''])
ypos = np.arange(ylabels.shape[0])
xposM, yposM = np.meshgrid(xpos, ypos, copy=False)

zpos = result
zpos = zpos.ravel()

# this defines the dimensions of the actual boxes
# you can play with these values.
dx = 0.7
dy = 0.7
dz = zpos

# here, we define ticks, they are placed in the 'middle' of each bar
ax1.w_xaxis.set_ticks(xpos + dx / 2.)
ax1.w_xaxis.set_ticklabels(xlabels, rotation='vertical')
ax1.w_yaxis.set_ticks(ypos + dy / 2.)
ax1.w_yaxis.set_ticklabels(ylabels)

# here we define the colors of the bars, rainbow style
# you can play with these numbers
values = np.linspace(0.2, 1., xposM.ravel().shape[0])
colors = cm.rainbow(values)

# figure subtitle
# fig.suptitle('test title', fontsize=20)

# here, we define in the x axis the size of its ticks, its numbers
ax1.tick_params(axis='x', which='major', pad=0, labelsize=7)

# Here, we define the limits of y axis,
# NOTE that this defines WHERE bars will be placed
# IN relation to the rest figure,
#  their offset point
plt.ylim((-2, 5))

# this says if the grid will be printed
plt.grid(True)
# this defines the placement of the 3d plot in its placeholders,
# in the surrounding white space
# I was surprised! The below line is not needed at all!
# fig.subplots_adjust(left=0, right=0, bottom=0, top=0)

# this is the actual command to define the plot
# all 6 parameters that we previously defined, are placed here.
# colors is an extra parameter
ax1.bar3d(xposM.ravel(), yposM.ravel(), dz * 0, dx, dy, dz, color=colors)

# elevation and azimuth, basically, definition of the view angle
ax1.view_init(0, -95)

# here we define that we will place a second plot
# Neither this line is needed!
# ax1 = fig.add_subplot(112, projection='3d')

# To produce numbers from 0 according to how many data exist in 'result'
x = np.arange(0, len(result))

y = result
# I try to center the line in relation to the top of bars.
y += 5
# Produce more points in order to make the line to look nicer (300).
x_smooth = np.linspace(x.min(), x.max(), 300)
y_smooth = spline(x, y, x_smooth)

# smooth line sometimes went below zero in some extreme cases.
# Therefore I added this if statement to find these cases
# and increase the height of the smooth line so much points
# as the points that went below 0
if min(y_smooth) <= 0:
    y -= (min(y_smooth))-1
    y_smooth = spline(x, y, x_smooth)

# a trick to center the line to bars
x_smooth += 0.4
# here,i try to produce a 'z' array of so many zeros as the length
# of 'x_smooth line'
z = np.linspace(0, 0, len(x_smooth))

# here, we define the parameters of the second plot.
# ax1' symbol is duplicated
# in order to plot the line in the same plot with the barplot.
ax1.plot(x_smooth, z, y_smooth)

# this try to align the y title
ax1.annotate(
    '\n'.join(wrap('Duration of each Rythm (in sec)', 20)),
    xy=(0.20, 0.80), xytext=(0, 0), fontsize=8, color='steelblue',
    style='italic',
    xycoords='axes fraction', textcoords='offset points',
    bbox=dict(facecolor='mistyrose', alpha=0.3),
    horizontalalignment='center', verticalalignment='down')

# this try to align the x title
ax1.annotate(
    '\n'.join(wrap('Where Rythm is broken (in sec)', 20)),
    xy=(0.27, 0.06), xytext=(0, 0), fontsize=9, color='steelblue',
    xycoords='axes fraction', textcoords='offset points',
    bbox=dict(facecolor='peachpuff', alpha=0.3),
    horizontalalignment='center', verticalalignment='down')

# this try to center the bottom title
ax1.annotate(
    '\n'.join(wrap(nms, 100)), xy=(0.5, 0.07),
    xytext=(0, 0), fontsize=11,
    xycoords='axes fraction', textcoords='offset points',
    bbox=dict(facecolor='mediumorchid', alpha=0.3),
    horizontalalignment='center', verticalalignment='down')

# Eedefine path and filename in order to save in custom made filename
pathnm = '/'
filenm = nms
nflnm = '%s_3D.png' % filenm
npath = os.path.join(pathnm, nflnm)

# saving our plot
#fig.savefig(npath, bbox_inches='tight', pad_inches=0,figsize=(46,15),dpi=400)
plt.show(fig)
io[0:2]'code'

0 个答案:

没有答案